使用 AJAX 发布不起作用,无法获得 _POST 美元的价值


Posting With AJAX not working, Can't get $_POST value

所以我遇到了一个小问题。我正在一个网站上工作,这是我第一次使用 ajax 发布到页面。我有一个带有提交按钮和链接的表单。当按下提交按钮时,一切正常,但用户应该能够通过传递页面来单击链接,但我仍然需要一些信息发布到该页面,所以我用谷歌搜索 ho 在没有提交按钮的情况下发布,ajax 出现了,所以我想我会试一试。它似乎不起作用。这是我正在使用的代码。

 $('#chkEndAccDate').click(function(evt){
    alert("before ajax");
    var totalcost = $('#total_cost').val();
$.ajax({
    type: "POST",
    url: "http://sandbox.phareconsulting.com/complete_order.php",
    `enter code here`data: {cost : totalCost}
       });
   alert("after ajax");
});

当我尝试时,此代码也不起作用 $(document).on('click','#chkEndAccDate',function(){ 成本 = $('#total_cost').val(); $.post("http://www.sandbox.phareconsulting.com/complete_order.php", {成本:成本},函数(d){ 警报("发布"); }); });

现在在 php 文件中,我只是在做print_r($_POST);但 post 数组是空的。有人可以帮帮我吗?我认为我们中的一些人只是没有正确理解ajax。我以为我做到了,但我无法让它工作。

谢谢。

这应该是正确的语法:

data: "{'cost':'" + cost+ "'}"

使用这个 data:{cost: cost}用于发送数据。

使用此代码:

$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val(); 
$.post("http://sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
});
});

s.d和Thiefmaster已经编写了正确的语法,但是,更改变量的名称以避免混淆可能是个好主意。

var totalCost = $('#total_cost').val();

然后使用:

data: {cost : totalCost}

使用 jQuery 表单插件发送 ajax 表单是个好主意,这将自行获取数据并将其发送到表单操作 URL。
该插件还为您提供了控制发送过程的功能。这是一个例子:

    var bar = $('#progressBar');
    var percent = $('#percent');
    var status = $('#status');
    $('#form-id').ajaxForm({
        beforeSend: function() {
            //validate the data 
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
           // draw a progress bar during ajax request
            var percentVal = percentComplete + '%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        complete: function(xhr) {
            bar.width("100%");
            percent.html("100%");
        }
    });

进度条的 html :

    <div id="progress">
      <div id="bar"></div >
      <div id="percent">0%</div >
    </div>

.css:

    #progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
    #bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
    #percent { position:absolute; display:inline-block; top:3px; left:48%; }