2017-06-03 15 views
-1

我是wordpress和插件的新手,但對php,javascript和html有合理的控制。我爲wordpress創建了一個插件,它生成一個收集產品規格信息的頁面(表單)。 [它實際上是一些連續的形式,但爲了簡單起見,可以說它是一個。我不想「提交」表格,因爲每張表格上都有很多字段,我不想在完成之前「提交」,並且他們已準備好轉到下一個表格]。如何向服務器發送變量名稱及其值,並接收計算出的響應

我希望能夠在用戶更改參數時(重新)計算產品價格。爲此,我希望能夠將已更改參數的名稱及其值返回給服務器(存儲計算的所有相關數據),然後執行計算並返回新的價格。目前我有一個javascript函數,它被稱爲「onChange」上的相關數據,然後修改代表總價格的div。如果我在本地計算這個值,這可以工作,但是現在我期望通過向服務器發送數據並接收計算出的響應來完成該功能,例如:

function total_price(arg,value) { 

    ***** send arg and value to server ***** 

    ***** receive total_price back from server ***** 

    var total_div = document.getElementById("total_price"); 
    total_div.innerHTML = "£"+total_price; 
} 

什麼代碼,我應該在這裏,以接收數據投入,我應該在服務器上,做計算並返回結果呢?

+2

請參閱:XmlHttpRequest在其響應事件處理程序(又名AJAX)中創建請求和更新頁面。 –

回答

0

我主要是在前端加載jQuery,所以我會發佈一個使用jQuery框架的答案。如果你不打算加載一個JavaScript庫,你很可能會在其他地方找到一個好的香草片段。

前端

var html_price = 1; // Whatever you need here 

// You'll notice that the ajaxurl variable below, is sent to the front-end in the second code snippet of this answer 
$.post(ajaxurl, { 
    action: "get_total_price", // action is a special parameter Wordpress is listening for 
    price: html_price 
}).done(function(price) { 
    // Price back from the server you can use in the DOM 
    // You should probably send this using JSON, this example only uses a string 
    console.log(price); 
}); 

後端

// Here is where Wordpress is waiting for that special action parameter 
// https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action) 

add_action('wp_ajax_get_total_price', 'get_total_price'); 
add_action('wp_ajax_nopriv_get_total_price', 'get_total_price');  

function get_total_price() { 
    $price = $_POST[ 'price' ]; 

    if($price) { 

     // do with the price what you want 
     echo $price; // Echo instead of return 
     exit; // Remember to close up the server response here 

    } else { 

     echo '0'; // Unrealistic, but guarantees a response 
     exit; 

    } 
} 

// Send the AJAX URL to the front end. There are more elegant ways to do this, but for the purpose of this answer, this should work. 
add_action('wp_head', 'add_ajaxurl_to_head'); 
function add_ajaxurl_to_head() { ?> 
    <script> 
     ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; 
    </script> 
<?php } 
+0

另外一個很好,更深入的答案,涵蓋了類似的問題,在這裏:https://stackoverflow.com/questions/18259241/proper-way-to-link-ajax-url – Theunis

+0

感謝您的幫助,我現在有: – AlanMason

+0

您是否能夠完成這項工作@AlanMason? – Theunis

0

最後,我得到它的工作(根據你的代碼,把握客戶端和服務器環境之間的差異,使用哪種語言,其中和什麼數據可以訪問)。謝謝你的幫助。 Web開發必須有一個單一的語言的範圍,這是可讀和上下文感知的? HeHo,我希望世界變得適合我!

相關問題