簡體   English   中英

AJAX成功調用定義的函數

[英]AJAX Success call a defined function

我在成功調用外部函數時遇到麻煩。 理想的解決方案是讓我還將一些參數傳遞給函數!

success: writeToConsole("successful");

Javascript:

$(document).ready(function () {
  $(".portalControls").find(".syncButton").click(triggerSync);    
});

function triggerSync(e) {
  e.preventDefault();
  $.ajax({
    type: "GET",
    url: "sync",
    dataType: "text",
    success: writeToConsole,
      error: writeToConsole
    }
  });
}

function writeToConsole(consoleText) {
  $.find("portalConsole").text(consoleText);
}

HTML:

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/js/scripts.js"></script>

我得到的錯誤: "Uncaught TypeError: $.ajax is not a function" 我從未在服務器上收到請求。

編輯:問題是與另一頁上的jQuery苗條腳本有關。 刪除該錯誤已修復。

您正在使用jQuery的苗條版本。 它不支持ajax調用。 使用以下

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

更新 出以下JSfiddle

正如@Santosh所說,請確保在您的頭中添加以下代碼:

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

另外我發現您的代碼中有一些錯誤,我試圖找出您要實現的目標並從中創建代碼,您應該看看這是您想要的

 $(document).ready(function() { $(".portalControls").find(".syncButton").click(triggerSync); }); function triggerSync(e) { e.preventDefault(); $.ajax({ type: "GET", url: "sync", dataType: "text", success: writeToConsole("fine"), error: writeToConsole("error") }); } function writeToConsole(consoleText) { $(".portalConsole").text(consoleText); } 
 <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <div class="portalControls"> <button class="syncButton"> click </button> </div> <div class="portalConsole"> </div> 

對於我首先發現的問題,這里還有一個}

    success: writeToConsole,
    error: writeToConsole
}
^
});

其次,我不知道您為什么使用$.find("portalConsole").text(consoleText); ,如果要更改文本,我將使用$(".portalConsole").text("text here...")還要注意,這里沒有. 或在portalConsol之前輸入#

只需添加上面的CDN腳本標簽

<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM