【问题标题】:How to send a var in ajax function call to send POST? [duplicate]如何在 ajax 函数调用中发送 var 以发送 POST? [复制]
【发布时间】:2015-11-20 22:18:25
【问题描述】:

我调用了一个 ajax 函数,我想发送一个 var,例如:

     <a href="next.php" onclick="sendajax()">reload</a>

从我的 php 页面使用 ajax 函数 POST 发送:

  <script>
 function sendajax(){   
    var xmlObj=new XMLHttpRequest();

   xmlObj.open("POST","miscript.php", true);

   xmlObj.setRequestHeader("content-type","application/x-www-form-urlencoded");

   xmlObj.onreadystatechange = function(){
    if(xmlObj.readyState == 4 && xmlObj.status == 200){
        document.getElementById("response").innerHTML = xmlObj.responseText;
   }
  }
   xmlObj.send('name=Status');
 }
 </script>

如何添加这个 var 以发送喜欢的内容?:

  function sendajax(myVar){ 
 ....
  xmlObj.send(myVar);

我正在尝试添加这个,但只发送文本。

谢谢!

编辑 我认为我的问题不会重复,因为我想从点击的链接发送 vars,而不是像这样写到 var 中:

    var params = "lorem=ipsum&name=binny";

我知道如何编写并传递它,我问:如何将此 var 发送到函数并将其添加/连接到字符串中。不使用表格..谢谢!!!!!!!

我认为我的解释是正确的。

【问题讨论】:

  • ^ 检查第二个答案,使用 FormData

标签: javascript php jquery ajax


【解决方案1】:

为什么不使用 jQuery?

您可以将按钮作为 this 传递给函数。

<a href="#" onclick="sendajax(this)">clickme</a>
function sendajax(button) {
    var myVar = $(button).html(); // Example. Take some datas from the button

    $.ajax({
        url: 'miscript.php',
        type: 'POST',
        data: { param1: myVar, param2: 'something_else'} ,
        success:function(dataFromAjaxResponse, typeFromAjaxResponse) {
            // When the request was successful proceed coding here
            // Variable dataFromAjaxResponse is the response (output) from your php site. 
        },
        error: function(dataFromAjaxResponse) {
            console.log(dataFromAjaxResponse);
        }
    });
}

【讨论】:

    【解决方案2】:

    通常,我使用 $.ajax()... 像这样:

    $.ajax({
      method: "POST",
      url: "some.php",
      data: { name: "John", location: "Boston" }
    })
      .done(function( msg ) {
        alert( "Data Saved: " + msg );
      });
    

    http://api.jquery.com/jquery.ajax/

    【讨论】:

      猜你喜欢
      • 2016-04-25
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多