[英]jQuery Ajax - Call and response
我對Javascript,jQuery和Ajax還是很陌生,所以我有幾個問題。
我想要的是:在我的JavaScript中發出Ajax請求,控制器將把OBJECT作為參數。 在從后端接收到作為流的響應之后,Controller將以JSON返回結果(在javascript中成功執行)。 但是,在這里我有點不確定。 是否應返回JObject或原始JSON字符串(例如在JsonConvert的幫助下)?
在我的WebApiConfig.cs中:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Controllers參數列表中的對象類型:
public class Credentials
{
public string Email { get; set; }
public int CustomerID { get; set; }
public string Reference { get; set; }
}
要調用的Contoller方法:
public HttpResponseMessage GetOrderInfo(Credentials credentials)
{
// Create Url with appended Credential properties
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
var response = (HttpWebResponse)httpWebRequest.GetResponse();
var responseStream = response.GetResponseStream();
var rawJson = new StreamReader(responseStream).ReadToEnd();
// var json = JObject.Parse(rawJson);
return Request.CreateResponse(HttpStatusCode.OK, rawJson);
}
Javascript:
function get_order_info(email, customerId, reference) {
/* This is where I want the Ajax call to the correct controller, taking an object
as a parameter */
}
現在,我的問題是:
考慮到我希望以Credential對象作為參數的特定Controller方法被調用,這樣的$ Ajax調用將如何?
我想返回JSON格式,這是Controller方法GetOrderInfo中的正確方法嗎?
對於最后一個問題,我有點傻。 如果返回正確的JSon格式,如何從響應中訪問它:
success: function (response) {
/* response.responseText ?? */
}
謝謝,最好的問候
將Ajax排除在外;
您的正常網絡請求會如何?
GET請求的示例: http://localhost:8080/api/controller1/get_order_info?email=value1&&customerId=value2&&reference=value3
此調用是否識別您的Controller方法,接受請求參數並為您提供json對象?
如果是,那么您可以發出Ajax GET或POST請求來執行相同的操作。
通過JQuery的Ajax POST請求:
$.post( "http://localhost:8080/api/controller1/get_order_info", { email: "value1", customerId: "value2", reference:"value3" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
https://api.jquery.com/jQuery.post/
注意:在這種特定情況下,應該有一些服務器組件可以接受請求並創建Credentials
對象,並根據傳入的請求參數設置屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.