2016-08-09 55 views
1

我正在使用JQuery Ajax將數據從一個域發送到另一個域中的ASP.NET頁面。我能夠從ASP.NET頁獲得迴應,但我無法從JQuery Ajax發送數據。這裏是我的代碼:如何將數據從JQuery Ajax發送到ASP.NET頁面?

 $.ajax({ 
      url: 'http://somewebsite/dbd/leap.aspx', 
      data: '{ year: "' + $('#txtYear').val() + '"}', 
      type: 'POST', 
      async: true, 
      cache: false, 
      dataType: 'jsonp', 
      crossDomain: true, 
      contentType:"application/json; charset=utf-8", 
      success: function (result) { 
       console.log("inside sucess"); 
       console.log("result: " + result); 
      }, 
      error: function (request, error) { 
       // This callback function will trigger on unsuccessful action     
       alert('Error!'); 
      } 
     }); 

我可以達到leap.aspx頁面。注意http://somewebsite只是一個佔位符。

leap.aspx有以下幾點:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="leap.aspx.cs" Inherits="_Default" %> 
<%=output %> 

leap.aspx.cs有以下幾點:注意我用Request.Params["year"]度日Ajax呼叫,但沒有運氣過去的一年的價值。

using System; 

public partial class _Default : System.Web.UI.Page 
{ 
public string output = ""; 
protected void Page_Load(object sender, EventArgs e) 
{ 
if (Request.Params["callback"] != null) 
    { 
     output = Request.Params["callback"] + "('" + GetData(Request.Params["year"]) + "')"; 
    } 
} 

[System.Web.Services.WebMethod] 
public string GetData(string year) 
{ 
return "From outer space! " + year; 
} 

}

當我運行這段代碼,在控制檯中我看到

「的結果:從外太空!」

但我沒有看到由Ajax發送的數據。我正在使用JSONP,因爲我正在進行跨域請求以繞過同源策略。我沒有收到任何錯誤。我只是沒有得到從ASP.NET頁面返回的年份的價值。

我該如何獲得這一年?

+0

我認爲在很多情況下,你希望以.json有圍繞重點行情和價值......改變你的'數據的格式:'到{「year」:「2001」}修復它? –

回答

0

更改數據設定刪除這樣的語錄:如果數據是{年:「2001」}

data: { year: $('#txtYear').val() }, 
+0

謝謝馬特。更改爲數據:{year:「'+ $('#txtYear')。val()+'」}解決了問題。我現在回到了一年。 – citm09

相關問題