早上好社区,
目前我正在用 Javascript 编写一个插件(为名为“Construct 2”(scirra.com) 的开发工具管理帐户),它使用 PHP 后端并通过 AJAX 与其通信。
当后端脚本只包含简单的任务时,比如...
<?php header("Access-Control-Allow-Origin:*"); // Allow all origins
$InputAction = $_POST["Action"]; // Eventhandler
if ($InputAction == "Register") {
echo("-400") } ?>
一切正常。但是,当我放入我想包含的更复杂的东西时,我总是遭到 CORS 拒绝:
XMLHttpRequest cannot load http://api.proxy.wtf/debug.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.14:50001' is therefore not allowed access. The response had HTTP status code 500.
上面错误我用的代码:
<?php
header("Access-Control-Allow-Origin:*"); // Allow all origins
require('includes/config.php'); // Prerequisite
/** Numeric callbacks (!negative values!)
-200 Registration successful; validation mail sended
-250 Username OK
-300 Username too short
-301 Username already in use
-302 Password too short
-303 Invalid email address
-304 Email already in use
-305 Error while registration
-400 Illegal request
**/
$InputAction = $_POST["Action"]; // Eventhandler
$InputUsername = $_POST["Username"]; // Requesting username
$InputMailaddress = $_POST["Mailaddress"]; // Requesting mail address
$InputPassword = $_POST["Password"]; // Requesting password
if ($InputAction == "Register") { // Action: Register
if(strlen($InputUsername) < 3){ // Check Username length
$error[] = 'Username is too short.';
echo("-300");
} else { // Check if username already exists
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $InputUsername));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo("-250");
if(!empty($row['username'])){ // If username already taken
$error[] = 'Username provided is already in use.';
echo("-301");
}
}
}
else {
echo("-400");
}
?>
有人对我有什么想法吗,我做错了什么?语法不包含错误(据我所知)。除非我不是 php/ajax 方面的专家,否则我认为这里的某些人可以帮助我指出/指出我的错误所在。我愿意学习 - 所以如果我犯了一个常见的错误,请告诉我 :s
祝你有美好的一天, 棕褐色
编辑: 这是 JS 部分 http://pastebin.com/iABkRmt0 (请求内容从 ~115 行开始——它是 C2 的完整 JS SDK 脚本,对此感到抱歉——但至少它是完整的;))
最佳答案
你必须使用jsonp,
我给你一个Jsonp用法的例子,希望这对你有帮助
$.ajax({
url: "http://data.acgov.org/resource/k9se-aps6.json?city=Alameda",
jsonp: "$jsonp",
dataType: "jsonp"
}).done(function(data) {
console.log("Request received: " + data);
});
关于javascript - 从 JS 到 PHP;另一个 CORS 问题(似乎是),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36856200/