如何将变量名称及其值发送到服务器并接收计算的响应

时间:2017-06-03 18:26:05

标签: javascript php wordpress server

我是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 个答案:

答案 0 :(得分:0)

我主要在前端加载了jQuery,所以我将使用jQuery框架发布一个答案。如果你不打算加载一个javascript库,你很可能会在其他地方找到一个好的vanilla代码段。

前端

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 }

答案 1 :(得分:0)

At last I got it working (based upon your code and grasping the difference between the server and client contexts, which language to use where and what data is accessible). Thanks for your help. There must be scope for a single language for web development which is readable and context aware? HeHo, there I go wanting the world to change to suit me!!