以下是包含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/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>
浏览器中WCF服务URL返回的JSON数据如下:
{"shipmentDetails":[{"Name":"AAA","Number":"123"},{"Name":"BBB","Number":"321"}]}
当我点击按钮时,浏览器中没有响应,并且没有在firebug中显示错误。
请帮我解决我的错误。
谢谢。
答案 0 :(得分:1)
使用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'
});