0

我使用 jCart 作为购物车,从 jCart 可以得到变量$subtotal.

但是,当更改购物车中的某些内容时,该变量$subtotal在页面重新加载之前不会更改。

是否可以使用 jQuery 来更新$subtotal页面点击.click(function())

4

3 回答 3

3

The question is flawed to begin with.

PHP runs server side. When all PHP is done, it gets presented to the browser and all the variables are gone. Maybe you're echoing some of them, so they are "there" in literal format, but there is no PHP variable anymore to update.

You can update something, like a javascript variable that you have filled before trough PHP, or a HTML value that got set by PHP. This can be done by reload, or this can be done by using an AJAX post, then some PHP magic, then a return + assign, but you are NOT replacing/reloading any PHP variables.

It is REALLY important to understand that there is no $subtotal anymore whatsoever after you've send the page to the browser. Please look into server side versus client side!

于 2012-04-26T09:21:48.437 回答
0

我在这里为您制作了一个 ajax 帖子示例的 JSFiddle(无需重新加载页面):http: //jsfiddle.net/5RjUt/1/

查询

$("#button").click(function(){ // click function fired

var subtotal = $("#subtotal").val()
var dataString = 'subtotal=' + subtotal;

$.ajax({ // ajax post
    type: "POST",
    url: "YOUR_PHP_PAGE.php", // post data to this URL
    data: dataString,
    cache: false,
    success: function(html){ // this is where you can set a success callback
       $("#subtotal").val("You're new value");
    }
});
return false; // this tells the page not to refresh

)};​
于 2012-04-26T09:11:27.937 回答
0

有点不清楚您要做什么

但这里有一些建议。


仅使用 jQuery 更新客户端:

如果您需要更新网页上的某些可见值,假设您只需要增加或减少subtotal网页上显示的值,那么您可以使用 jQuery 来执行此操作,而无需任何服务器端处理。

客户端处理(Javascript / jQuery):

var subtotal = 0;

// Add value to subtotal and update div displaying subtotal
function addToSubtotal( value ) {
    subtotal += value;
    $('#subtotal').html(subtotal);
}

// When DOM is loaded...
$(document).ready( function(){
    // Bind onclick event to every <a class="buyme">
    $('.product').on('click', 'a.buyme', null, function(e){
        // Buyme link clicked, add <span class="pricetag"> value to subtotal:
        addToSubtotal( parseInt( $(this).siblings('.pricetag').html() ));
    });
});

​</p>

客户端处理(HTML):

<div class="product">
    <a class="buyme" href="#">Add to subtotal</a><br/>
    <span class="pricetag">55</span>€
</div>
<br/>
<span id="subtotal">0</span>​​​​​​​​​​​

或者使用 jQuery.ajax() 来更新服务器端:

您也可以使用它来更新 JS 变量,尤其是在服务器检查并返回subtotal. 在这种情况下,实际上是服务器为您返回新的小计值。

似乎您的 PHP 变量$subtotal首先是从某个数据存储系统中读取的,它可能看起来总是在那里,例如在执行$myStore = new onlineStore();.

我假设它$subtotal已经可用并且包含一些一致的整数值。

AJAX 更新请求的代码(服务器端和客户端):

如果正确使用,这将更新server sidePHP 变量,并检索它们以与client sidejQuery / Javascript 一起使用。

但是,此功能不会开箱即用,只能用作您完整实施的起点。

客户端处理(javascript/jquery):

function updateSubtotalAtServer( args ) {
    $.ajax({
        type: 'POST',
        url: 'processing.php', // <= Request url
        // Add method=ajax, we use PHP to check that value
        data: $(args).serialize()+"&method=ajax",
        // processing.php returned some data:
        success: function(data){
            // Try decoding data as JSON encoded string:
            try { 
                dataobj = $.parseJSON(data);
            } catch (e) { 
                dataobj = null;
            }
            // Check if JSON return value decoded successfully:
            if (dataobj !== null) {
                // Successfully decoded JSON, log values to console.
                // ...update subtotal <span> to display it for user:
                $('#subtotal').html( dataobj.subtotal );
                console.log( dataobj );
            } else {
                // Result was not JSON string (server error).
            }
        }
    });
}

// Create new object to be used as array:
var arrayobject = new Object;
// Add this value at server side to $subtotal:
arrayobject.addtosubtotal = 55;
// Then send ajax request to server:
updateSubtotalAtServer( yourvariables or array object );

服务器端处理(php):

// Variable that needs updating:
/* $subtotal is already available, ..read above.. */ 

if (isset($_POST['method']) && $_POST['method'] == 'ajax') {
    // Update variables:
    $subtotal += (int)$_POST['addtosubtotal'];
    // Put all data together what is needed at client side:
    $ajaxreply = array( 'subtotal' => $subtotal, 'othervalue' => 'FooBar' );
    // Return it to browser:
    echo json_encode( $ajaxreply );
    // JSON reply will fail if there is any additional output after that.
    exit;
}

更多阅读/可能有用的答案:
关于 jQuery.ajax 的另一个答案,专注于 REST、表单和数据数组
关于 jQuety.ajax 的另一个答案,从服务器获取数据

于 2012-04-26T09:41:41.923 回答