我如何在jQuery中创建一个关联数组(或一些类似的替代)并通过ajax将该数组发送到PHP页面,以便我可以使用PHP来处理它?
像这样……
// jQuery
if($something == true) {
data[alt] = $(this).attr('alt');
data[src] = $(this).attr('src');
else if ($something == "something else") {
data[html] = $(this).html();
}
然后,使用.ajax()函数发送此数组
// jQuery
$.ajax({
data: /* somehow send my array here */,
type: 'POST',
url: myUrl,
complete: function(){
// I'll do something cool here
}
});
最后,用PHP解析这些数据……
// PHP
<img alt="<?PHP echo $_POST['alt']; ?>" src="<?PHP echo $_POST['src']; ?>" />
我已经对这个主题进行了一些谷歌搜索,并且已经读过你不能用javascript创建一个关联数组,所以我真的只是在寻找一些替代方案.提前致谢.
解决方法:
您可以将数据作为对象传递给$.ajax()
,如下所示:
var data = {};
if ($something == true) {
data.alt = $(this).attr('alt');
data.src = $(this).attr('src');
}else if ($something == "something else") {
data.html = $(this).html();
}
$.ajax({
data: data,
type: 'POST',
url: myUrl,
complete: function(){
// I'll do something cool here
}
});
这将为帖子序列化,内部使用$.param(obj)
将其转换为POST,例如:
alt=thisAlt&src=thisSrc
要么:
html=myEncodedHtml
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。