【问题标题】:Form submit stopping JSON objects from displaying表单提交阻止 JSON 对象显示
【发布时间】:2011-10-11 00:57:17
【问题描述】:

我正在构建一个带有单个字段和一个提交按钮的表单。用户输入一个值,单击按钮,该值被发送到一个 .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>

【问题讨论】:

    标签: php javascript jquery html json


    【解决方案1】:

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

    $('.button').live('click', function (e)  {
    
      e.preventDefault();
    
      //rest of your code
    
    });
    

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

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

    【讨论】:

    • 非常感谢,当我单击按钮时它现在正在工作,它返回 JSON 代码。目前,.ajax 方法中的 q var 被硬编码为“star”。单击按钮后,如何获取文本字段的值并将其传递给 q var?
    • 如果我正确阅读了您的问题,那么只需将该行替换为:q: $('[name=myanswer]').val()。很高兴我能帮上忙:p
    • 约翰,这行得通。我真的不能感谢你。我想我有过这样的日子!真的,真的很感激!
    猜你喜欢
    • 2018-11-07
    • 2020-10-06
    • 2017-02-10
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多