表单提交停止显示JSON对象

时间:2011-10-10 16:53:46

标签: php javascript jquery html json

我正在构建一个包含单个字段和提交按钮的表单。用户输入一个值,单击该按钮,该值将发送到.ajax方法,该方法向Google Shopping API发送POST请求。

目前,每当我点击提交按钮后尝试运行该方法时,都不会收到JSON响应。只要我点击按钮上的代码,它就会重新出现。

任何帮助都会很棒。

<!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> 

<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>

1 个答案:

答案 0 :(得分:2)

e.preventDefault()添加到您的处理程序中。还记得将event参数传递给函数......

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

  e.preventDefault();

  //rest of your code

});

此外,在这种情况下没有理由使用.live()。我只是将它直接绑定到元素 -

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

});