发送JSON数据到PHP Web服务

发送JSON数据到PHP Web服务

问题描述:

我向服务器发送该呼叫:发送JSON数据到PHP Web服务

var Message = {}; 
Message['islands'] = '1-15-13'; 
Message['newMessageText'] = 'this is test message'; 
$.ajax({ 
    url: "sendnote.php", 
    type: "POST", 
    data: Message, 
    dataType: "json", 
    contentType: "charset=utf-8", 
    success: function (data) { 
     alert(data["result"]); 
    }, 
    error: function (data) { 
     alert(data["result"]); 
    } 
}); 

,并在服务器上(sendnote.php)我有

print_r($_POST); 

只是为了检查我得到了什么,但在Firebug中检查响应后,我发现这个数组是空的。

我在做什么错误的发送数据?

在此先感谢!

PS我已经检查了此主题的上一篇文章,但仍然有问题。

+0

嗯,你是如何得到数据[“结果”]? sendnote.php脚本中是否有更多内容没有显示?或者它只是print_r($ _ POST)? – Gohn67 2012-03-27 06:27:02

+0

当我运行该代码时,可以看到正在发布的数据。 – Quentin 2012-03-27 06:27:47

+0

昆汀,你是对的,我也看到了,但在Firebug中,我发现我的$ _POST是空的。那就是问题所在。这就是为什么我只是print_r($ _ POST) – 2012-03-27 07:14:53

的问题是将contentType

试试这个:

jQuery的

$(document).ready(function(){ 
var Message = {}; 
    Message['islands'] = "1-15-13"; 
    Message['newMessageText'] = 'this is test message'; 

$.ajax({ 
     url: "sendnote.php", 
     type: "POST", 
     data: Message, 
     dataType: "json", 
     success:function(data) { 
      alert("Islands: "+data.islands+", Message: "+data.newMessageText); 
      }, 
     error:function(data) { 
      alert('error'); 
     } }); 
}); 

PHP

<?php 
    echo json_encode($_POST); 
?> 

print_r($_POST)不给出JSON响应。你甚至知道当不使用AJAX时请求的实际回复是什么样的?

尝试echo json_encode($_POST); - 这应该打印出有效的JSON。

或我想补充一点,你可能已经忘记了PHP的<?php ?>打开和关闭标签

+0

我认为他正在检查Firebug中的ajax请求。但是,是的,我认为你是正确的,如果sendnote.php只是print_r($ POST); – Gohn67 2012-03-27 06:29:16

+0

Gohn67,你是对的。我只是在Firebug中检查$ _POST。我在我的代码$ jsonresponse = json_encode($ _ POST)和其他代码创建JSON响应。在客户端,我收到JSON响应,显然是空的$ _POST结果。 – 2012-03-27 07:19:51

+0

@DevetiPutnik你可以发布'sendnote.php'中的所有代码吗? – Joseph 2012-03-27 07:21:05