0

我可以使用 ajax GET 方法将数据发布到 php 页面,但是在向 POST 方法添加更多参数时遇到问题。下面是我使用的代码。因为我能够从 php 脚本中得到响应:

    if(XMLHttpRequestObject) {
   XMLHttpRequestObject.open("POST", url,true);XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
 XMLHttpRequestObject.onreadystatechange = function()
 {
    document.getElementById('statuses').innerHTML = msg1;
   if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
var content = XMLHttpRequestObject.responseText;
 $(document).ready(function(){
    $('#statuses').text(content);
    });
}
 }
XMLHttpRequestObject.send("id=" + id);
}

现在假设我决定使用另一个代码来发送使用 jquery 更容易的数据,我如何从 php 脚本中获取响应?下面是第二个代码:

     $(document).ready(function(){ 
    // get values
     cc = $('#ft').attr('value');
     cop = $('#copt').attr('value');

     // send to processing PHP script
     $.ajax({
        type: "GET",
        cache: false,
        url: "processor.php",
        data: "cctotal="+ cc +"&coptotal="+ cop + "&id="+ id + "&get=" + 'update',
        success: function(){
            $('#processing').fadeIn(function(){
            var content = 'Customer Account Updated !' ;
            $('#statuses').text(content);
            });
        }
            });

     });
4

2 回答 2

1

ajax 的默认 contentType 是'application/x-www-form-urlencoded; charset=UTF-8', 和 cahce 所以你不需要设置它,XMLHttpRequestObject你在 jQuery 中进行的普通 JS 调用看起来像:

$(function() {
    $.post(url, , function(content) {
        $('#statuses').html(content);
    });
});

要使用一些添加的数据执行 POST 请求,您可以执行类似的操作

$(function(){ 
    cc = $('#ft').val();
    cop = $('#copt').val();

    $.ajax({
         type: 'POST',
         url: url,
         cache: false,
         data: {cctotal: cc, coptotal: cop, id: id, get: 'update'}
    }).done(function(content) {
         $('#processing').fadeIn(function(){
             $('#statuses').text('Customer Account Updated !');
         });
    });
});
​

您将在服务器上的 POST 超全局中访问该数据。例如在 PHP 中它将是:

$cc  = $_POST['cctotal'];
$cop = $_POST['coptotal'];
$id  = $_POST['id'];
$get = $_POST['get'];
于 2012-08-26T07:55:27.963 回答
0
//Try this

 $(document).ready(function(){ 
    // get values
     cc = $('#ft').attr('value');
     cop = $('#copt').attr('value');

     // send to processing PHP script
     $.ajax({
        type: "GET",
        cache: false,
        url: "processor.php",
        data: "cctotal="+ cc +"&coptotal="+ cop + "&id="+ id + "&get=" + 'update',
        success: function(data){
            $('#processing').fadeIn(function(){
            var content = 'Customer Account Updated !' ;
            $('#statuses').text(content);
            });
            alert(data) //server response here
        }
            });

     });
于 2012-08-26T07:04:50.407 回答