开发者

Using PHP and AJAX to send / receive JSON using a form

I'm trying to build a simple form with a single text field and a submit button that when clicked, posts the value to a $.getJSON method which retrieves the JSON response and outputs it to webpage.

Is there anyway I can do this dynamically using AJAX and PHP? Would I need to use a $.ajax method to POST the value to a PHP page or can I just refractor my existing method.

$.getJSON(
    "https://www.googleapis.com/shopping/search/v1/public/products?callback=?",
    {
        key: "keyhere", 
        country: "US", 
        q: searchterm, 
        alt: "json" 
    },
    function(data) {

        $.each(data.items, function(i, item){

            if (item.product.images.length > 0) // sanity check
            {

            //global variables
            var link = item.product.images[0]['link'];
            var title = item.product.title;

                var listData = "<li>" + title + "</li>" + '<img title="' + title + '" src="' + link + '" />';

                $('#lists').append(listData);

                var img = $("<img/>").attr("src", link);
                $("<a/>").attr({href: link, title: "image title"}).append(img).appendTo("#images");

                console.log(data)
            }
        });
    }
);

EDIT:

开发者_StackOverflow社区

Thanks to SBerg413, I managed to change the method to .ajax and it works perfectly, working example below:

var apiKey = "key";
var country = "US";
var apiurl = "https://www.googleapis.com/shopping/search/v1/public/products?callback=?";
var search = 'starwars';

$.ajax({
    url: apiurl,
    dataType: 'jsonp',
    data : 
    {
        key: apiKey, 
        country: country, 
        q: search,
    },
    success: function(data) {

         $.each(data.items, function(i, item){

            if (item.product.images.length > 0) // sanity check
            {

            //global variables
            var link = item.product.images[0]['link'];
            var title = item.product.title;

                var listData = "<li>" + title + "</li>" + '<img title="' + title + '" src="' + link + '" />';

                $('#lists').append(listData);

                var img = $("<img/>").attr("src", link);
                $("<a/>").attr({href: link, title: "Courtesy of James"}).append(img).appendTo("#images");

                console.log(data)
            }
        });


        // console.log(data);
        console.log(data)
    }
});


The jQuery getJSON method is just a shorthand for the ajax() method. http://api.jquery.com/jQuery.getJSON/ So, you should be able to use either. However, the getJSON method uses a GET. So, if you specifically want to use a POST, you're better off using the ajax() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜