【问题标题】:Set var in $.ajax() method using input from a form?使用表单输入在 $.ajax() 方法中设置 var?
【发布时间】:2011-10-10 13:20:52
【问题描述】:

我的目标听起来很简单,但目前我很难理解它。

获取表单中文本字段的值并将其传递给 $.ajax() 方法中使用的 var,该方法发布到 Google Shopping API 并获取 JSON 格式的响应,然后将其输出到网页..

到目前为止,我已经让 $.ajax 方法完美运行,它从 Google 购物返回 JSON 对象。我还可以将这些输出到 HTML 字符串中并在网页上显示结果。

这就是我正在使用的..

<!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 country = "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>

使用表单和 javascript,是否可以将 var 'search' 更改为用户在文本字段中输入的内容,在 .ajax 方法中指定我想要返回的内容?

任何建议都会很棒!

【问题讨论】:

  • 您只想将var search = $(this).parents('form').serialize(); 替换为var search = $('#textField').val(); 吗?
  • 好吧,我希望在提交表单时将表单中文本字段的值传递给 var 'search'。

标签: javascript jquery html ajax json


【解决方案1】:

你可以在你的 $.ajax 调用中替换 q: search 到 q: $(this).parents('form').serialize()

【讨论】:

  • 好的,为此我还需要提交表单。我应该将哪个事件绑定到表单?
  • 不确定这是否是您要查找的内容,但是当 是提交表单的代码时,我会这样做:$("form").submit(function(e) { e.preventDefault(); .... code block ... });
【解决方案2】:

这是我在 ajax 表单方面的做法。

  1. 构建一个无需 js 或 jQuery 即可实际工作的表单。

  2. 使用 jQuery 将事件绑定到此表单 preventDefault() 并通过 $.post 提交。

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多