开发者

Form submit stopping JSON objects from displaying

I'm building a form with a single field and a submit button. A user enters a value, clicks the button and the value is sent to a .ajax method which sends a POST request to the Google Shopping API.

At the moment, whenever I try and run the method once the submit button is clicked the JSON response isn't being received. As soon as I remove the code on button click, it reappears.

Any help would be great.

<!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="h开发者_如何学Cttp://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> 

<form id="myform">
   <input type="text" name="myanswer" value="test">
   <input type='submit' class="button" name="submitButton" value='submit'>
</form>

<script>

    var apiKey = "key-removed-from-stackoverflow";
    var country = "US";
    var apiurl = "https://www.googleapis.com/shopping/search/v1/public/products?callback=?";


    $(document).ready(function() {
        $('.button').live('click', function()  {
    $.ajax({
    type: "POST",
    url: apiurl,
    dataType: 'jsonp',
    data : 
    {
        key: apiKey, 
        country: country, 
        q: "star"   

        },
    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)
     }
    });
});
});


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


add e.preventDefault() to your handler. Also remember to pass in the event parameter into the function too...

$('.button').live('click', function (e)  {

  e.preventDefault();

  //rest of your code

});

Also, there is no reason to use .live() in this situation. I'd just bind it directly to the element -

$('.button').click(function () {

});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜