2011-10-10 71 views
0

我的目标听起来相当简单,目前我遇到了一个问题让我头脑发热。

它是获取表单中文本字段的值,并将其传递给$ .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“搜索”是什么用户在文本字段中输入,在阿贾克斯方法指定我想要返回的内容?

任何建议将是伟大的!

+0

你只是要替换'VAR搜索= $(this).parents('form')。serialize();''var'search = $('#textField')。val();'? –

+0

好吧,我希望表单中的文本字段的值在提交表单时传递给var'search'。 – jcrowson

回答

2

你可以更换问:到q搜索在$就调用:$(本)。家长( '形式')序列化()

+0

好的,为了做到这一点,我需要提交表格。我应该将哪个事件绑定到表单上? – jcrowson

+1

不知道这是你在找什么,但是当是提交表单的代码时,我会这样做: '$(“form”)。submit(function(e){ e。 preventDefault(); .... code block ... });'' –

1

下面是我如何做到这一点,当涉及到Ajax形式。

  1. 构建一个实际上没有js或jQuery的表单。

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

相关问题