开发者

Set var in $.ajax() method using input from a form?

My goal sounds fairly simple, at the moment i'm having an issue getting my head around it.

It is to get the value of a text field in a form and pass it to a var used in an $.ajax() method which posts to the Google Shopping API and gets a response in JSON which is then outputted to a webpage..

So far i've got the $.ajax method working perfectly, which returns JSON objects from Google Shopping. I can also output these into an HTML string and display the results on a webpage.

This is what I am using..

<!DOCTYPE html>
<html>
<head>
  <style>
  #images { padding:0; margin:0; overflow: hidden;}
  #images img { width:200px; height:200px; border:none;}
  #lists li { display: table;}
  #lists img { width:200px; height: 200px; }
  </style>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<h1 id="title"></h1>
<p id="description"></p>
<div id="images"></div> 
<div id="lists"></div> 

<script>


var apiKey = "key";
var c开发者_C百科ountry = "US";
var apiurl = "https://www.googleapis.com/shopping/search/v1/public/products?callback=?";
var search = $(this).parents('form').serialize();

$.ajax({
    type: "get",
    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 me"}).append(img).appendTo("#images");

                console.log(data)
            }
        });

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

</script>
</body>
</html>

Using a form and javascript, is it possible to change the var 'search' to what a user enters in a text field, in the .ajax method to specify what I want to return?

Any suggestions would be great!


You could replace the q: search in your $.ajax call to q: $(this).parents('form').serialize()


Here is how I do it when it comes to ajax forms.

  1. build a form that actually works without js or jQuery.

  2. use jQuery to bind an event to this form, preventDefault() and submit it via $.post.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜