2013-11-01 65 views
0

所以,我有一個JS .post調用,通過控制器操作向表中添加一行。然後它將該行的主鍵返回到視圖。我需要將這個整數插入到第二個.post調用的數據中,我需要對另一個控制器進行調用。如何使用之前調用的數據進行第二次JS .post調用?

更新的Javascript 首先來看看我的javascript:

var result = $.post('/Question/CreateSimpleQuestion/', (data), function (result) { 
            $.post('/Question/CreateSimpleQuestionChoice/', ({ 
                   "QuestionId":result, 
                   "DisplayText": text, 
                   "OrderNumber": order, 
                   "is_correct": false}), 
                    null, 'application/json'); 
       }, 'application/json'); 

這些是被稱爲控制器操作:

 // 
    // POST: /Question/CreateSimpleQuestion 

    [HttpPost] 
    public JsonResult CreateSimpleQuestion(Question question) 
    { 
     question.is_counted = true; 
     question.DateCreated = DateTime.Now; 
     db.Questions.Add(question); 
     db.SaveChanges(); 
     return Json(question.QuestionId, JsonRequestBehavior.AllowGet); 
    } 

    // 
    // POST: /Question/CreateSimpleQuestion 

    [HttpPost] 
    public JsonResult CreateSimpleQuestionChoice(QuestionChoices choice) 
    { 
     db.QuestionChoices.Add(choice); 
     db.SaveChanges(); 

     return Json(choice, JsonRequestBehavior.AllowGet); 
    } 
+0

你看過jQuery的'post()'的文檔嗎?它似乎有示例說明你需要什麼:http://api.jquery.com/jQuery.post/。 json被瀏覽器自動反序列化成一個javascript對象。嘗試一下你自己應該很容易。 – rliu

回答

2

你第Ajax調用創建成功處理程序(鑰匙可用的地方),並且在該成功處理程序中,您將進行第二次ajax調用,然後您可以將該密鑰傳遞給它。

var result = $.post('/Question/CreateSimpleQuestion/', data, function(result) { 
    // make your second ajax call here and you can use the result of the first 
    // ajax call here 
    var dataq = { 
     "QuestionId": result.QuestionId, // data from first ajax call here 
     "DisplayText": text, 
     "OrderNumber": order, 
     "is_correct": false 
    }; 
    $.post('/Question/CreateSimpleQuestionChoice/', dataq, function(result2) { 
     // examine result of second ajax function here 
     // code goes here 
    }, 'application/json'); 

}, 'application/json'); 

下面是與嵌入,所以你可以跟蹤它在調試控制檯的進步,但我個人更喜歡只設置斷點和檢查變量控制檯調試語句的版本。

console.log("Position 1"); 
console.log(data); 
var result = $.post('/Question/CreateSimpleQuestion/', data, function(result) { 
    // make your second ajax call here and you can use the result of the first 
    // ajax call here 
    var dataq = { 
     "QuestionId": result.QuestionId, // data from first ajax call here 
     "DisplayText": text, 
     "OrderNumber": order, 
     "is_correct": false 
    }; 
    console.log("Position 2"); 
    console.log(dataq); 
    $.post('/Question/CreateSimpleQuestionChoice/', dataq, function(result2) { 
     // examine result of second ajax function here 
     // code goes here 
     console.log("Position 3"); 
     console.log(result2); 
    }, 'application/json'); 

}, 'application/json'); 
+0

你可以打ajax電話嗎?我第一次嘗試,因爲我意識到這是我應該做的,但我一直得到關於原始類型的錯誤。 – schumacherj

+0

@schumacherj - 我不知道你想要的第二個Ajax調用看起來像什麼或JSON看起來像第一個返回。 – jfriend00

+0

@schumacherj你的第二個Ajax調用有什麼問題?這似乎是真正的問題。 – foolmoron

相關問題