2012-01-16 82 views
7

我想讓jquery與Web服務進行通信!Jquery - 使用POST請求,這是不允許的錯誤

function Test(item) { 
    $.ajax({ 
     type: 'POST', 
     url: 'WebService.asmx/Test', 
     data: '{ "Item" : "' + item + '" }', 
     contentType: 'application/json; charset=utf-8', 
     dataType: 'json', 
     success: function (msg) { 
      alert("oi"); 
     }, 
     error: function (msg) { 
      alert('Get Details Failure: ' + msg); 
     } 
    }); 
}; 

using System.Web; 
using System.Web.Services; 
using System.Data.SqlClient; 
using System.Web.Script.Services; 
using System.Web.Script.Serialization; 

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
[ScriptService] 
public class WebService : System.Web.Services.WebService { 

    public WebService() {} 

    [System.Web.Services.WebMethod] 
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] 
    public string Test(string Item) 
    { 
     JavaScriptSerializer js = new JavaScriptSerializer(); 
     string strJSON = js.Serialize(Item); 
     return strJSON; 
    } 

我得到以下信息:

{"Message":"An attempt was made to call the method \u0027Test\u0027 using a POST request, which is not allowed.","StackTrace":" at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"} 
+0

嘗試使用'GET' – 2012-01-16 17:15:15

回答

18

Web服務方法標有ScriptMethodAttribute指定UseHttpGet = true。嘗試刪除該參數,或將其設置爲false。這是阻止POST工作的原因。

2

好,用GET請求,然後(或更改Web服務方法接受POST)

function Test(item) { 
    $.ajax({ 
     type: 'GET', 
     url: 'WebService.asmx/Test', 
     data: {Item: item }, /* note change here, data is NOT a string! */ 
     contentType: 'application/json; charset=utf-8', 
     dataType: 'json', 
     success: function (msg) { 
      alert("oi"); 
     }, 
     error: function (msg) { 
      alert('Get Details Failure: ' + msg); 
     } 
    }); 
}; 

注意,data參數不是字符串(和,特別是,它不是JSON)。你應該傳遞一個JavaScript對象。