【发布时间】:2014-08-08 18:13:00
【问题描述】:
我有一个使用 jquery 来处理 ajax 的 Angular 应用程序(我在这个问题上使用 jquery 在 $http 上取得了更多进展)。我正在尝试将 json 数据发送到 php 并成功完成(php 读取它并通过标头返回数据)。我的问题是 $.ajax 无法识别成功,它失败并返回响应的解析错误。
这是我的 javascript:
function loginUser() {
var target = "../data/user.php";
var data = {
"userName": "me",
"userPass": "pass",
"action": "login"
};
$.ajax({
url: target,
type: "POST",
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function(data) {
console.log(data);
}
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
这是我的 php:
$data = file_get_contents("php://input");
$objData = json_decode($data);
print_r($objData);
这是我在 php 标头中得到的响应:
stdClass Object
(
[userName] => me
[userPass] => pass
[action] => login
)
非常感谢您的帮助
【问题讨论】:
-
你为什么用
$.ajax用Angular的$httpdocs.angularjs.org/api/ng/service/$http -
如果你设置了正确的标题,你也不需要使用
php://input。如果将标头设置为Content-Type: application/x-www.form-urlencoded,则可以在另一端使用常规的 php 变量($_GET、$_POST、$_REQUEST)。如果您要发送一个 JS 对象,只需在发送时使用 jQuery 的 param 函数 ->$.param(data)
标签: php jquery ajax json angularjs