2013-10-21 45 views
1

我嘗試了所有周圍,因爲這在我看來,一個非常普遍的(NUBEE?)問題搜索,但沒有爲我工作...所以這裏是的Javascript的Ajax回調函數沒有定義錯誤

要正確的切入追逐,我的Razor代碼(稍後顯示)將ajax表單發佈到MVC4操作,但可以正常工作,但任何嘗試向窗體添加回調函數(OnSuccess,OnBegin等)都會導致運行時錯誤(未定義回調函數)失敗。這是我的Chrome瀏覽器的錯誤信息的圖像時,會出現異常後右:

JSChromeError

這是形式的代碼:

@using (Ajax.BeginForm("AskQuestion", null, 
     new AjaxOptions() { 
      OnSuccess = "endAskQuestion" }, 
     new { id = "askQuestionForm" })) 
    { 
     @Html.AntiForgeryToken() 
     @Html.ValidationSummary(true) 

     <fieldset> 
      <legend>@ViewBag.Controller</legend> 
      <br /> 
      @{ var investigationID = Model.Investigation.InvestigationID; } 
      @Html.HiddenFor(model => investigationID) 
      <input type="submit" class="button" value="שלח היגד"/> 
      <input type="button" id="cancelEdit" class="button" value="בטל עריכה"/> 
     </fieldset> 
    } 

和腳本在其內部endAskQuestion是定義如下:

$(document).ready(function() { 

    //deleted several Jquery and JS functions... 

    // callback function definition 
    function endAskQuestion() { 
     alert("adad"); 
    } 
}) 

另外,我看到一些文章指出JQuery和Ajax腳本的引用很重要,所以這裏是ht毫升的頭節與文獻:

<head> 
    <meta charset="utf-8" /> 
    <title>RTInvestigation</title> 
    <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" /> 
    <link href="/Content/css?v=_WuF_JGHabtqdWNcwICWILVG9A391eZyF0GO24jlq9U1" rel="stylesheet" type="text/css" /> 
    <link rel="stylesheet" type="text/css" /> 
    <script> </script> 
    <meta name="viewport" content="width=device-width" /> 
    <script src="/Scripts/jquery-1.8.2.js"></script> 

    <script src="/Scripts/jquery-ui-1.8.18.js"></script> 
    <script src="/Scripts/jquery-ui-1.8.20.js"></script> 

    <script src="/Scripts/jquery.unobtrusive-ajax.js"></script> 
    <script src="/Scripts/jquery.validate.js"></script> 
    <script src="/Scripts/jquery.validate.unobtrusive.js"></script> 

</head> 

我不知道爲什麼剃鬚刀創建了兩個jQuery的UI版本引用......我找不到原因。

回調函數怎麼沒有定義?

感謝您的幫助

+0

您的代碼正在生成某種形式的IIFE,但它沒有定義函數'endAskQuestion'。 –

回答

1

採取endAskQuestion$(document).ready功能。另外,在每個javascript代碼行末尾使用分號,因爲這通常會引發未定義的錯誤。

$(document).ready(function() { 

    //deleted several Jquery and JS functions... 

}); // added semicolon here... 

// callback function definition should be moved outside 
function endAskQuestion() { 
    alert("adad"); 
} 
0

endAskQuestion的範圍僅限於jQuery在文檔準備就緒時調用的匿名函數。正如ps2goat所說,您需要將其從$(document).ready回調中取出。通過這種方式,它將在全球範圍內定義,並且可以通過關閉您使用的AJAX的callbakc來訪問。閱讀關於範圍界定,關閉和匿名的信息。

+0

有一種感覺,函數的範圍是問題,應該真正閱讀JS腳本中的範圍。 TNX – user1707621