我有一个javascript方法代码段,如下所示
var tempUrl = "http://A.com:8081/TestService/serviceMethod";
jQuery.ajax({
url:tempUrl,
type: 'POST',
data:"getDatareq="+encodedata,
contentType: 'application/json',
dataType:'text',
success:function(result){
jQuery(".loadingMsg").html("");
jQuery(".loadingMsg").hide();
getApptDtls(result);
},
complete:function(result){
jQuery(".loadingMsg").html("");
jQuery(".loadingMsg").hide();
jQuery(".popupContent").show();
jQuery.unblockUI();
我将此方法包含在html中,该html托管在其他服务器中,其中包含网址http://B.com:8081
当我运行此html并调用此方法时,A.com中的serviceMethod未被命中。这可能是什么问题?
非常感谢任何帮助。
答案 0 :(得分:1)
使用 JSONP 。
JSONP或“带填充的JSON”是JavaScript中使用的通信技术。它提供了一种从不同域中的服务器请求数据的方法,这是由于相同的原始策略而被典型Web浏览器禁止的。
jQuery的:
var tempUrl = "http://A.com:8081/TestService/serviceMethod";
$.ajax({
url:tempUrl,
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
},
});
PHP:
<?php
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");"; // 09/01/12 corrected the statement
?>