問題描述
在 Javascript/Jquery Ajax 調用中使用 WCF 服務 (Consuming WCF service in Javascript/Jquery Ajax call)
我在以下路徑上託管/發布了 WCF 服務 ‑
newslettersubscriptiondev. mercola.com/NewsletterSubscriptionService.svc
想在Jquery Ajax Call
中調用WCF服務
jQuery編寫的代碼‑
<script type="text/javascript" src="JS/jquery‑2.1.4.js"></script>
<script type="text/javascript" src="JS/jquery‑2.1.4.min.js"></script>
<script type="text/javascript">
function cityClickJQuery() {
$.ajax({
type: "POST",
url: "http://newslettersubscriptiondev.mercola.com/NewsletterSubscriptionService.svc/CheckEmailaddressValidateOnly",
data: { EmaillAddress: 'pranav.bilurkar28@gmail.com', Source: 'ArticleBody' },
processData: false,
contentType: "application/json; charset=utf‑8",
dataType: "json",
success: function (data) {
alert('success');
alert(data.d);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
alert(jqXHR);
}
});
}
</script>
上面的JS代碼中CheckEmailaddressValidateOnly
是Service中定義的C#方法,需要2個參數。
設計代碼‑
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btn1" runat="server" OnClientClick="cityClickJQuery();" Text="click" />
</div>
</form>
</body>
上面的JS代碼不起作用。
請幫忙。
參考解法
方法 1:
First you should verify that you include attribute
[WebInvoke (ResponseFormat = WebMessageFormat.Json)]
Second you should use
data:JSON.stringify({EmaillAddress: 'pranav.bilurkar28@gmail.com', Source: 'ArticleBody'}),
The JSON.stringify is defined in http://www.json.org/js.html.
One more update After the successful return of data you will see that the data returned back should be accessed not with data.d.EmailAddress, but with data.EmailAddress instead. ASMX web‑service place the data in the property d, but not WCF service.
方法 2:
Change data: { EmaillAddress: 'pranav.bilurkar28@gmail.com', Source: 'ArticleBody' },
To
data: JSON.stringify({ EmaillAddress: 'pranav.bilurkar28@gmail.com', Source: 'ArticleBody' }),
(by user5426326、Shahid Manzoor Bhat、Mohammed47)