我知道有些人问过这个问题,但我的问题不同了。当JS和php文件都在同一个域中时,它们就像魅力一样,但当我将PHP文件放在远程服务器上并调用该服务器时,我没有得到任何结果。以下是我的代码。请让我知道我做错了什么。我需要编辑我的htaccess文件吗?
- - - - - - - - JS
$("document").ready(
function(){
$(".js-ajax-php-json").submit(
function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
jQuery.support.cors = true;
$(".the-return").html('<img src="loading.gif" />');
$.ajax({
type: "POST",
dataType: "json",
url: "http://********/response.php",
data: data,
success: function(data) {
$(".the-return").html(
"Favorite beverage: " + data["favorite_beverage"] + "<br />Favorite restaurant: " + data["favorite_restaurant"] + "<br />Gender: " + data["gender"]
);
}
});
return false;
});
});
---- ----- PHP
header('Access-Control-Allow-Origin: *');
header('Access-Control-Request-Method: POST');
header('Access-Control-Request-Headers: X-PINGOTHER');
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) {
$action = $_POST["action"];
switch($action) {
case "test": test_function(); break;
}
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
$return["json"] = json_encode($return);
echo json_encode($return);