在AJAX中传递多个变量?

时间:2013-11-10 23:07:40

标签: javascript ajax

我一直在尝试在线跟踪一个示例,我将使用AJAX传递变量到PHP

它工作但我设法只通过使用AJAX传递1个变量,但我需要传递多个变量,我试图添加它但它没有工作任何帮助将不胜感激

我尝试像var url = 'ajax.php?js_var=' + js_var + gender;一样添加它,但它只是在同一行打印出来。

 <html>
  <head>
    <title>Pass variable from PHP to JavaScript - Cyberster's Blog'</title>
  </head>
  <body> 
    <a href="#" id="link">Click me!</a>
    <div id="update"></div>

    <script type="text/javascript">
        var js_var = "M";    
        var gender = "hey";
        document.getElementById("link").onclick = function () {        
            // ajax start
            var xhr;
            if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers
            else xhr = new ActiveXObject("Microsoft.XMLHTTP");  // for IE

            var url = 'ajax.php?js_var=' + js_var + gender;
            xhr.open('GET', url, false);
            xhr.onreadystatechange = function () {
                if (xhr.readyState===4 && xhr.status===200) {
                    var div = document.getElementById('update');
                    div.innerHTML = xhr.responseText;
                }
            }
            xhr.send();
            // ajax stop
            return false;
        }
    </script>
  </body>
  <?php
    if (isset($_GET['js_var'])) $php_var = $_GET['js_var']  ;
    else $php_var = "<br />js_var is not set!";

     if (isset($_GET['gender'])) $php_var1 = $_GET['gender'] ;
    else $php_var1 = "<br />js_var is not set!";

echo $php_var;
echo $php_var1;

?>

1 个答案:

答案 0 :(得分:2)

快速回答......

var url = 'ajax.php?js_var=' + js_var + '&gender=' + gender;

更好的回答

var params = {
    "js_var": js_var,
    "gender": gender
};

var queryParams = Object.keys(params).map(function(k) {
    return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
}).join('&');

var url = 'ajax.php?' + queryParams;

如果您需要支持IE版本&lt; 9,请参阅Array.prototype.mapObject.keys的以下填充程序。