gpt4 book ai didi

javascript - 使用表单输入在 $.ajax() 方法中设置 var?

转载 作者:行者123 更新时间:2023-11-28 21:15:35 25 4
gpt4 key购买 nike

我的目标听起来相当简单,但目前我在思考它时遇到了问题。

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

到目前为止,我已经让 $.ajax 方法完美运行,它从 Google Shopping 返回 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 方法中指定我想要返回的内容?

任何建议都会很棒!

最佳答案

您可以将 $.ajax 调用中的 q: search 替换为 q: $(this).parents('form').serialize()

关于javascript - 使用表单输入在 $.ajax() 方法中设置 var?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7713387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com