我正在做一个简单的ajax请求到另一个域,像这样:
<script type="text/javascript">
$(function() {
$('.clik').click(function() {
$.ajax({
type: "POST",
url: "http://sub.mydomain.com/test.php",
crossDomain: true,
dataType:"jsonp",
success: function(data) {
$('p.txt').html(data['no']);
}
});
});
});
</script>
</head>
<body>
<p class="clik">Halleluja</p>
<p class="txt"></p>
这是sub.mydomain.com上的test.php页面
<?
header('Access-Control-Allow-Origin: http://mydomain.com');
// Begin Session
require_once('cl.session.php');
$session = new Session();
$session->start_session('test', false);
// Access Database
require_once('cl.database.php');
$login_db = new Database('user', 'pass', 'accounts', 'test');
$login_pdo = $login_db->PDO;
include "fn.check_login.php";
if(checkLogin($login_pdo) == true) {
// We start out by checking if the request has been made using AJAX
if (is_ajax()) {
echo "this is working";
} else {
echo "this is not working!";
}
} else {
echo 'You are not authorized to access this page, please login. <br/>';
}
// Function to check if the request is an AJAX request
function is_ajax() {
// BOOLEAN return if AJAX
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?>
返回一个语义问题。
如果我只是回显一些基本的文本:
<?
echo "Hello World!";
?>
它仍然返回一个语义问题。
谁能告诉我出了什么问题?首先,JSONP请求不能是POST
(只能是GET
)。但我倾向于假设jQuery忽略了无效的type
。JSONP 本质上是 GET
。
你的回复是无效的。您已经告诉jQuery,希望服务器提供JSONP响应。但是你的回答不是JSONP。
JSONP响应应该是这样的:
callback({
"property": "value",
"anotherProperty": 42
})
…其中回调的名称(上面的callback
)取自请求的查询字符串。因此,例如,如果请求是http://sub.mydomain.com/test.php?callback=foo
,响应将使用foo
作为回调的名称:
foo({
"property": "value",
"anotherProperty": 42
})
jQuery将自动为您的请求添加callback=
查询字符串参数,并为您生成相应的函数,该函数将传入的数据调用ajax
成功处理程序
我认为你可能需要使用jquery postMessage插件(或类似的,如果有一个)。很长一段时间以来,我尝试过,但检查你是否从服务器加载脚本,你想调用(认为我尝试过,并在过去失败了,但嘿-它值得一个bash -报告如果它做)。