【发布时间】:2014-01-08 06:32:28
【问题描述】:
我现在很头疼,因为我整天都遇到这个问题,但仍然无法解决。我在 Google 和 StackOverflow 上看了几个小时,尝试了很多方法(包括从 JSON 更改为 JSONP,检查 PHP 的标头,localhost 测试),询问朋友等,但我仍然卡住了。也许只是一个细节,我不知道。
我正在开发一个 Android 移动应用程序,为此,我在主机(比如 example.com)上有一个 PHP 网络服务,它工作正常,因为我使用 PHP WS JSON 客户端进行了测试。问题是我现在使用 jQuery、JSON 和 Ajax 从我计算机上的 JS 文件调用这个 WS,我从 Google Chrome 的调试器控制台得到以下响应:
- 就绪状态:4
- 状态文本:“确定”
- responseText:(我需要的,没有错误)
但是在服务器的响应中,我总是收到错误回调,而不是成功。我读它是因为服务器无法正确解析 JSON,但我真的不知道。
我的代码留给你。
来自 CLIENT.JS:
$.ajax({
type: "POST",
crossDomain: true,
contentType: "application/json utf-8",
dataType: "json",
url: "http://www.example.com/ws/webservice.php/" + methodName,
data: JSON.stringify(window.parameterArray),
success: function (response)
{
alert('Success!');
window.resultVar = "Success! " + response;
console.log(response);
},
error: function (response)
{
alert('Error');
window.resultVar = "Error: " + response;
console.log(response);
}
});
来自 SERVER.PHP:
<?php
header('Access-Control-Allow-Origin: *'); //I have also tried the * wildcard and get the same response
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Content-type: application/json; charset=utf-8');
require_once "mobilefuncts.php";
$methodName = str_replace($_SERVER["SCRIPT_NAME"]."/", "", $_SERVER["REQUEST_URI"]);
if (isset($methodName))
{
$param = (array)json_decode($HTTP_RAW_POST_DATA);
$access = new MobileAccess(); //From mobilefuncts.php
$result = call_user_func_array(array($access,$methodName), $param); //Calls the method
echo json_encode($result);
}
?>
有谁知道可以做什么?也许,正如我之前所说,问题只是一个细节。我真的不知道,我对这种事情有点陌生。
感谢正手!
更新:
我刚刚意识到 Chrome 控制台告诉我这个:
GET http://localhost:81/.../cordova_plugins.json 404 (Not Found)
这可能是问题的原因吗?
更新 2:
看这里,我有线索。我在错误函数中添加了更多参数,得到了这个结果:
(error的变化是从function(response)到function(jqXHR, textStatus, errorThrown))
jqXHR.responseText: [an array with the info I'm asking]
errorThrown: "SyntaxError: Unexpected token"
【问题讨论】:
-
contentType: "application/json utf-8"缺少分号? -
“响应”在说什么?
-
'response' 说,除其他外,我在主帖上的内容:readyState:4 status:200 statusText:“OK” responseText:(我需要什么,没有错误)
标签: javascript php jquery json web-services