2010-08-31 117 views
1

這是我的代碼上的jQuery/AJAX參數:如何獲得服務器

$.ajax({ 

      type: "POST", 
      url: "Default.aspx", 
      data: "category=2&city=Boston", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      processData :false, 
      error: function (json) { 
       alert(json.statusText); 
      }, 
      success: function (json) { 
       alert(json.statusText); 

      } 
     }); 

我怎樣才能讓我的參數(category=2&city=Boston)到服務器? 請求參數始終爲null

回答

4

你不寫關於服務器的任何信息,但你同時使用contentTypedataType包含JSON。所以可能你想發送JSON數據到服務器,並接收JSON數據。來自字符串「category = 2 & city = Boston」的數據不是JSON格式。

您應該將字符串「category = 2 & city = Boston」替換爲「category = 2 & city =」Boston「'。我建議你閱讀我的舊的答案How do I build a JSON object to send to an AJAX WebService?和使用JSON.stringify功能(json2.js的一部分,它可以從http://www.json.org/js.html下載)

所以,你的代碼應該更好地修改以下

var myCategory = 2; 
var myCity = "Boston"; 
$.ajax({ 
    type: "POST", 
    url: "Default.aspx", // probably it should by a ASMX amd not ASPX page? 
    data: { category: myCategory, city: JSON.stringify(myCity) }, 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    error: function (json) { 
     alert(json.statusText); 
    }, 
    success: function (json) { 
     // you should probably modify next line because json can be an object 
     alert(json.statusText); 
    } 
}); 
0

喜歡的東西這對我來說在JAVA中調用一個servlet非常有用,但不確定.NET是否值得一試。

$.ajax({ 
    type: "GET", 
    url: "/Default.aspx?category=2&city=Boston" 
    //more config stuff here 
});