我尝试生成动态JSONP回显,但在js ajax调用后我的检查器工具中出现错误:
Uncaught ReferenceError: jQuery191019304498913697898_1365868235193 is not defined index.php:1
PHP:
<?php
header('Content-type: application/javascript; charset=utf-8');
$array = array();
array_push($array, array('name' => 'A', 'host' => 'A.com'));
array_push($array, array('name' => 'B', 'host' => 'B.com'));
//$jsonp = json_encode($array, JSON_FORCE_OBJECT);
$jsonp = json_encode($array);
if(isset($_GET['callback']))
{
echo $_GET['callback'].'('.$jsonp.')';
}
else
{
echo $json;
}
?>
JS:
$.ajax({
username: username,
password: password,
url: url,
dataType: 'jsonp',
crossDomain: true,
ifModified: true,
success: function (data, status, jqXHR) {
console.log(data);
$.each(data, function(index, value) {
console.log(value['name']);
});
}
});
Ajax呼叫响应:
jQuery191019304498913697898_1365868235193([{"name":"A","host":"A.com"},{"name":"B","host":"B.com"}])
你有什么想法吗? 我的错误在哪里?
由于
答案 0 :(得分:4)
试试这个。
// test.php文件
<?php
header('Content-type: application/json; charset=utf-8');
$array = array();
array_push($array, array('name' => 'A', 'host' => 'A.com'));
array_push($array, array('name' => 'B', 'host' => 'B.com'));
$jsonp = json_encode($array);
if(isset($_GET['callback'])){
echo $_GET['callback'] . '(' . $jsonp . ')';
}else{
echo $jsonp;
}
?>
// js file
<script type="text/javascript">
function myCallback(data, status){
console.log(data);
}
$.ajax({
url: 'test.php',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'myCallback',
crossDomain: true,
ifModified: true
});
</script>
请记住,如果您没有指定回调,jQuery auto会为回调生成别名。您的回调实际上设置为"jQuery191019304498913697898_1365868235193()"
。通过手动设置回调,它应该工作。
答案 1 :(得分:0)
更改此
header('Content-type: application/javascript; charset=utf-8');
到
header('Content-type: application/json; charset=utf-8');