2013-07-27 111 views
2

我使用asp.net web服務.asmx來傳輸json數據。我有以下代碼似乎沒有工作。Json對象返回不能在asp.net中使用webservice(.asmx)

$.ajax({ 
      type: "POST", 
      url: "../../App_Code/jsonWebService/getValue", 
      data: "{}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (output) { 
       alert(output); 
       $(config.captchaQuestion).html(output[0] + " + " + output[1] + " ="); 
       $(config.captchaHidden).val(output[2]); 
      } 
     }); 

而且我裏面ASMX文件的jsonWebService.cs代碼:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
using System.Web.Script.Services; 
using System.Web.Script.Serialization; 

/// <summary> 
/// Summary description for jsonWebService 
// </summary> 
[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment  the following line. 
[System.Web.Script.Services.ScriptService] 
public class jsonWebService : System.Web.Services.WebService { 


[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public Array getValue() 
{ 
    Random getRandom = new Random(); 
    int rand1 = getRandom.Next(0, 9); 
    int rand2 = getRandom.Next(0, 9); 
    int sum = rand1 + rand2; 
    int[] jsonObject = new int[3] { rand1, rand2, sum }; 
    return jsonObject; 
} 

} 

而且我得到Forbidden錯誤提前403感謝。

回答

0

您不允許直接瀏覽app_code文件夾中的文件。您必須提供asmx文件的路徑並使用webservice名稱。

變化

url: "../../App_Code/jsonWebService/getValue", 

url: "../../jsonWebService.asmx/getValue", 
+0

不工作。其實我從根文件夾中調用兩個層次結構的asmx,並且如果我使用url:「/ jsonWebService/getCaptcha」,並且404方法不允許錯誤,如果我使用類似url,它會給出404未找到錯誤:「jsonWebService/getCaptcha」 。 – user79307

+0

url:「../../jsonWebService.asmx/getValue」工作。謝謝。 – user79307

0

的網址不能爲:

"../../App_Code/jsonWebService/getValue", 

因爲App_Code文件是存儲類/模型的特殊文件夾/任何其他代碼文件a nd我們可以直接訪問該文件夾中的文件,而無需指定文件夾路徑(App_Code);;)

+0

是@VidhyaSagarReddy你是對的,那麼我對asmx web服務非常陌生,我想我應該鏈接到在添加.asmx文件後在App_Code內部創建的類,但後來我知道我會鏈接到該類。 asmx文件,它將在App_Code中執行.cs文件。然後一切順利。謝謝。 :) – user79307