我有2個基本的測試應用程序,我做Ajax請求。在調用ajax請求後,對於第一個請求,我需要在檢索值之前解析ajax data.responseText。對於第二個,我可以直接使用訪問值。爲什麼有時我必須parseJSON,有時候不需要做Ajax請求?
代碼的第一個應用程序:
@using (Ajax.BeginForm("JsonAdd", "People", new AjaxOptions { OnComplete = "JsonAdd_OnComplete" }))
{
...
}
function JsonAdd_OnComplete(data) {
var json = $.parseJSON(data.responseText);
if (json.Success) {
$("#PersonList").html(json.PartialViewHtml);
}
$("#addPersonModal").slideToggle();
$("#message").html(json.Message);
}
正如你所看到的,我需要獲取值之前,首先解析data.responseText。
這裏是第二應用:
@using (Ajax.BeginForm("_NewPersonToKeepInformed", "General", new { id = "NewPersonToKeepInformed" }, new AjaxOptions { Confirm = "Are you sure ?", HttpMethod = "POST", OnSuccess = "AddedSuccess" }))
function AddedSuccess(response) {
alert(response.message);
}
對於這一個,我直接中科院訪問值。
UPDATE
這裏是我的控制器的操作方法:
public JsonResult JsonAdd(AddPersonViewModel AddPersonModel)
{
...
return Json(new
{
Success = true,
Message = "The person has been added!"
});
}
這裏是第二個:
public JsonResult _NewPersonToKeepInformed(NewPersonToKeepInformedViewModel viewModel)
{
...
// return newly added person in a Json object
return Json(new { message = "Ajout effectué", firstName = viewModel.FirstName, lastName = viewModel.LastName, phone = viewModel.Phone, mail = viewModel.Mail });
}
爲什麼?
謝謝。
「@ using」語法是什麼? Ajax對象來自哪裏? – 2012-02-17 17:08:10
這是來自ASP.NET MVC語法。 Ajax對象來自那裏。 – Bronzato 2012-02-17 17:15:04
return Json(新的 { 成功= true, 消息=「該人已被添加!」 }); – Bronzato 2012-02-17 17:15:44