2013-03-13 81 views
1

我试图完成我的第一个AJAX交换,但是我在主页展开的时候会脱落。我有一个JSON字符串,我通过AJAX发送到一个php页面,verify.php,但是当我尝试接收这些数据时,$_POSTverify.php似乎完全是空的,如我的verify.php页面上的代码所示:

 
if (empty($_POST)) { 
    echo 'empty'; 
} else { 
    echo 'not-empty'; 
} 

我不知道这是为什么......我的AJAX代码似乎是好的:

 
$.ajax({ 
    type: 'POST', 
    url: 'serverside/verify.php', 
    data: data, // Where data is a javascript obj. which has been JSON.stringify'ied. 
    dataType: "JSON", 
    success: function(returned) { 
     console.log(returned); 
    }     
});

而且我时,我CONSOLE.LOG我的JSON字符串,我看到它是显示正常,甚至我的成功回调函数正在向控制台记录“空”(因为上面的if语句导致它回显'空')。所以交易似乎发生的很好,数据似乎正在发送很好,但它显然没有到达超全球化的$_POST。谁能解释为什么?

+0

请附上萤火虫截图!我认为PHP是好的 – 2013-03-13 08:28:25

回答

2

请检查您是否错过了任何步骤!

//声明一个变量

var jsonObj = {demo: 'this is just a simple json object'} 

//让我们转换JSON对象

var postData = JSON.stringify(jsonObj); 

//让我们把我们的字符串化JSON到一个变量张贴

var postArray = {json:postData}; 

$.ajax({ 
    type: 'POST', 
    url: "http://somedomain.local.com/phpfile.php", 
    data: postArray, 
    success: function(data){ 
     // Do some action here with the data variable that contains the resulting message 
    } 
}); 

我们需要将输入的字符串中的斜线去掉。然后我们只需运行json_decode php函数。之后,我们可以访问php对象,然后使用它,但我们喜欢。

if(isset($_POST["json"])){ 
    $json = stripslashes($_POST["json"]); 
    $output = json_decode($json); 

    // Now you can access your php object like so 
    // $output[0]->variable-name 
    } 

希望它会帮助!

+0

dataType - 您希望从服务器返回的数据类型。请参阅手册http://api.jquery.com/jQuery.ajax/ – 2013-03-13 08:32:32

+0

对不起,我简化了这个问题。该URL是正确的。 – ReactingToAngularVues 2013-03-13 08:40:47

+0

@防病毒请检查我更新的答案可能有帮助! – sandip 2013-03-13 08:57:04