[英]jQuery ajax json webservice error
如果有人指出這里出了什么問題,我當然會感激的。 我可以在web方法中設置一個斷點,但是它會被命中,但是它總是出錯。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AJAX_Test._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AJAX Test</title>
<script src="Scripts/jquery-1.7.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<button id="theButton">Click Here</button>
</form>
<script type="text/javascript">
$(function () {
$("#theButton").on("click", function () {
$.ajax({
type: "POST",
url: "AjaxWebService.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: AjaxSucceeded,
error: AjaxFailed
});
});
});
function AjaxSucceeded(data, status) {
alert("success");
}
function AjaxFailed(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
</script>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
namespace AJAX_Test
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class AjaxWebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
這是您的問題:
將此屬性添加到您的服務:
[ScriptService]
並將其添加到您的方法中:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
從javascript連接到服務時,它必須具有這些屬性。
您正在告訴jquery期望JSON數據作為來自ajax服務器的響應,但是您要發送一個裸字符串作為響應。 JSON字符串為"Hello World"
,並且服務器端代碼應為:
return "\"Hello World\"";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.