2017-03-12 87 views
-1

我一直在關注一個CRUD教程,位於這裏https://www.codeofaninja.com/2015/06/php-crud-with-ajax-and-oop.html。 我可以創造更新和刪除,但在阿賈克斯成功火災我得到一個錯誤:ajax成功後我打電話給showProducts()

showProducts() not defined

這樣的產品列表不會刷新。我不明白如何在沒有某種引用類型的情況下找到showProducts()。我知道showProducts()的作品,因爲它被稱爲在$(document).ready(function()

{ 
// show list of product on first load 
    showProducts(); 
}); 
works fine. 

    // send delete request to api/remote server 
    $.ajax({ 
     url: "http://localhost/api/product/delete.php", 
     type : "POST", 
     dataType : 'json', 
     data : JSON.stringify({ id: product_id }), 
     success : function(result) { 

      // re-load list of products 
      showProducts(); 
     }, 
     error: function(xhr, resp, text) { 
      console.log(xhr, resp, text); 
     } 
    }); 

} 
+1

是你的ajax和showProducts函數在同一個上下文中嗎? – Roljhon

+0

「showProducts()」如何定義?你在定義之前調用它嗎?在AJAX請求之前找到調用它的簡單方法,以確保不會造成範圍問題 – santi6291

+0

read-products.js是showProducts()的定義。 read-products.js位於index.php

0

因爲您的showProducts()函數未定義

只需創建($ Ajax調用)之前之一,它添加一些數據,例如:

// function to show list of products 
function showProducts(){ 
    // you can change those contents and add whatever you like. 
    $(document).ready(function() { 
     $("#emptydiv").html("<body> Add your prodects here </body>"); 
    }); 

} 

你想要把你的數據在HTML DIV:

<div id="emptydiv"> </div> 

what we add here inside (showProducts function) is just example . you can add what ever you want (depend on if you want to follow the tutorial completely or you want to add your Owen style and content) .

  • 和你提到的教程他們的鏈接添加這些內容:

    // function to show list of products 
    function showProducts(){ 
    
        // get list of products from the API 
        $.getJSON("http://localhost/api/product/read.php", function(data){ 
    
        // html for listing products 
        readProductsTemplate(data, ""); 
    
        // chage page title 
        changePageTitle("Read Products"); 
    
        }); 
    } 
    
+0

的路徑確定如果我把函數放在.ajax代碼的前面,它會很好。現在我必須複製確切的代碼並將其粘貼到以下文件 create-products.js,edit-products.js,delete.js這看起來像我在3個不同的位置複製代碼。 我以爲代碼需要一個路徑的功能showProducts() 像'read-products.js - > showProducts();' –