发布使用AJAX无法正常工作,无法获得$ _POST值

时间:2013-09-08 14:31:17

标签: php jquery ajax

所以我有一点问题。我正在网站上工作,这是我第一次使用ajax发布到网页。我有一个表单,上面有一个提交按钮和一个链接。当按下提交按钮时一切正常但用户应该可以通过传递页面点击链接但我仍然需要一些信息发布到该页面,所以我用Google搜索发布没有提交按钮和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");
});

此代码在我尝试时也不起作用     $(文件)。在( '点击', '#chkEndAccDate',函数(){       cost = $('#total_cost')。val();        $。员额( “http://www.sandbox.phareconsulting.com/complete_order.php”,       {cost:cost},function(d){     警报( “后”);        });       });

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

谢谢。

4 个答案:

答案 0 :(得分:1)

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

使用此代码:

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

答案 1 :(得分:1)

这应该是正确的语法:

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

答案 2 :(得分:1)

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

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

然后使用:

data: {cost : totalCost}

答案 3 :(得分:0)

使用jQuery Form Plugin发送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%; }