无法使用html中的javascript从url接收JSON数据
以下是包含javascript片段的HTML:无法使用html中的javascript从url接收JSON数据,javascript,jquery,html,json,wcf,Javascript,Jquery,Html,Json,Wcf,以下是包含javascript片段的HTML: <html> <head> <title>JSON</title> <script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js"> </script> <script language="javascript" type="text
<html>
<head>
<title>JSON</title>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js">
</script>
<script language="javascript" type="text/javascript" >
$(document).ready(function(){
$("testButton").click(function() {
$.ajax({
type: "GET",
dataType: 'jsonp',
contentType: "application/jsonp; charset=utf-8",
url: "http://localhost:4148/EIS.svc/getShipment/arun/arun",
success: function (data) {
obj = eval('(' + data + ')');
alert(obj);
var innerHtml = "";
document.getElementById('test').innerHTML=obj;
//'test' is ID of <label1>
document.getElementById('testlab').innerHTML=obj.shipmentDetails[0].Name;
//'testlab' is ID of <label2>
$("#test").html(innerHtml);
alert("JSON DATA");
alert(obj.shipmentDetails[0].Number);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error while retrieval – " + XMLHttpRequest.responseText+":"+textStatus+":"+errorThrown);
}
});
});
});
</head>
<body>
<input type="button" id="testButton" value="GET JSON"/>
<label id="test"></label>
<label id="testlab"></label>
</body>
</html>
当我点击按钮时,浏览器中没有响应,firebug中也没有显示错误
请帮我找出哪里出了错
谢谢。使用JSONP时,返回的数据应该包装在回调函数中,如下所示:
myCallback({"shipmentDetails":[{"Name":"AAA","Number":"123"},{"Name":"BBB","Number":"321"}]})
另外,将回调的名称添加到jQuery ajax定义中:
$.ajax({
type: "GET",
dataType: 'jsonp',
contentType: "application/jsonp; charset=utf-8",
url: "http://localhost:4148/EIS.svc/getShipment/arun/arun",
[...]
jsonpCallback: 'myCallback'
});
您的本地服务器是否也在端口4148上运行,或者您是否确定
arun
进程正在返回JSONP数据?谢谢@Borre。。你能帮助我如何在回调函数中包装返回的数据吗..这应该发生在服务器端代码中,类似于我回答中的第一个代码块。你能帮助我完成上述任务吗?我已经完成了在回调函数中包装返回数据的任务。
$.ajax({
type: "GET",
dataType: 'jsonp',
contentType: "application/jsonp; charset=utf-8",
url: "http://localhost:4148/EIS.svc/getShipment/arun/arun",
[...]
jsonpCallback: 'myCallback'
});