使用jQuery AJAX将JSON对象传递到PHP文件 [英] Using jQuery AJAX to pass JSON Object to PHP file
问题描述
我有一个像这样的JSON对象(分配给 var card;
):
I have a JSON object like this (assigned to var card;
):
{
card_no: "1",
card_name: "wwwgdefonru",
img_id: 1,
img_thumb: "albums/070915_E239/thumbs/001_wwwgdefonru.jpg",
img_hires: "albums/070915_E239/thumbs_hires/001_wwwgdefonru.jpg"
}
我想使用AJAX将其传递给php支持文件.
I want to pass this using AJAX to a php support file.
这是我的AJAX电话:
Here's my AJAX call:
jQuery.ajax({
method: 'POST',
url: ajax_file,
type: 'JSON',
data: card,
dataType: 'html',
cache: false,
success: function(html){
console.log('SUCCESSO');
jQuery('#debug').html(html);
},
complete:function(){
console.log('COMPLETE');
}
});
在我的PHP文件中(仅出于调试目的),我输出传递的数据,如下所示:
In my PHP file (just for debugging purposes) I output the passed data like so:
echo '<pre>';
print_r($_POST);
echo '</pre>';
AJAX调用成功完成.但是输出为空:
The AJAX call completes successfully. But the output is blank:
Array
(
)
我在哪里错了?
解决方案
我正在使用旧版本的jQuery进行项目(不要问...).通过查看文档( http://api.jquery.com/jquery.ajax/)我可以看到使用方法:'POST'
设置方法无效,因为我所使用的JQ版本不支持该方法.将其切换为 type:'POST'
并摆脱 type:'JSON'
对其进行了修复.
I am working on a project with an old version of jQuery (don't ask...). From looking at the docs (http://api.jquery.com/jquery.ajax/) I could see that setting the method using method: 'POST'
wasn't working because it isn't supported by the version of JQ I am using. Switching it to type: 'POST'
and getting rid of type: 'JSON'
fixed it.
即使我将其定义为 POST
,如果我没有查看网络"标签并看到请求方法为 GET
,我也不会发现这一点.
I wouldn't have spotted this had I not looked at the network tab and seen the request Method was GET
even though I have defined it as POST
.
推荐答案
The method of writing post method is in this way is so easy for you
$.post("your_php_file_url.php",
{
card_no: "1",
card_name: "wwwgdefonru",
img_id: 1,
img_thumb: "albums/070915_E239/thumbs/001_wwwgdefonru.jpg",
img_hires: "albums/070915_E239/thumbs_hires/001_wwwgdefonru.jpg"
},
function(data, status){
alert("Response Message" + data + "\nResponse Status: " + status);
});
在您的PHP站点中,您使用读取值
In your PHP site you read the values using
<?php
echo $_POST['card_no'];
?>
像这样,您可以获取其他值并完成工作!
like this you could get other values and do your works!
这篇关于使用jQuery AJAX将JSON对象传递到PHP文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!