2014-09-19 71 views
0
var ajaxData = {1: a, 2: b, 3: c, 4: d}; 
    $.ajax({ 
     type: "POST", 
     data : ajaxData, 
     etc 
     etc 

如果我在$ ajax中使用dataType: 'json',如何在我的php中捕获数据?如果不是我可以使用$ _POST ['1']等,但我打算使用贾森,因为我必须做$_POST['2']和更多..

回答

0

数据类型:JSON是Ajax调用的返回数据类型

数据是你的PHP文件/ servlet将被期待的参数。传递一个JSON见下面的例子,它是一个混合的JSON和正常参数

var params = {a:1, 
       b:2, 
       myJSON: JSON.stringify({data1:1, data2:2, data3:3})} 
    jQuery.ajax({ 
        type: "POST", 
        url: "some/url/of/php/file", 
        data: params, 
        dataType: "json", 
        success: function(response){ 
         // this should catch what ever is returned by your php file 
         alert(response) 
        }, 
        error: function(msg) { 
         alert('error'); 
        } 
       }); 

在你的PHP文件中,您可以访问所传递的数据是这样的$ _ POST [“一”],$ _ POST ['B '],$ _POST ['myJSON']

dataType是您的php文件的返回类型,而不是发送到php文件的参数。

参考这里了解更多信息 http://api.jquery.com/jquery.ajax/

+0

好了,现在在PHP端的问题,我有1进行检查1?我的意思是像isset($ _ POST ['1']) – user3522738 2014-09-19 09:07:51

+0

isset()检查是否传递参数或获取请求。在我的例子中,如果你想检查参数a,b和myJSON是否被传递,你必须说 'if(isset($ _ POST ['myJSON'])){' '/ *在这里用myJSON * /}' – andrex 2014-09-19 09:10:39

+0

所以只需检查整个json?必须在客户端进行验证? – user3522738 2014-09-19 09:34:53

0

您将有一个名为数据的请求中的php参数,将被解析为Json ,那么你只需要申请:

$data = json_decode($_POST[1]); 
0

我会去与

$.ajax(
    ... 
    data: {data: JSON.stringify({1: a, 2: b, 3: c, 4: d};)} 
) 

然后在服务器端我会使用json_decode函数来获取数据