使用AJAX处理时未传递PHP会话变量


PHP session variable not passed while processing with AJAX

我正在编写一个脚本,该脚本根据所选值返回答案。稍后会有多个值,但现在我只是在测试。php脚本通过AJAX调用,因此结果将显示在同一页面上。

唯一的问题是,在这种情况下,我的变量$brand没有被传递,所以脚本总是会返回我的else语句。我在echo中包含了这个变量,以检查它是否通过了,但事实并非如此。这里出了什么问题?

这是我的索引文件代码:

<?php
session_start();
?>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="JS/jquery-1.10.2.js" ></script>
<script>
        function myCall(){
            var request = $.ajax({
                url: "process.php",
                type: "post",
                dataType: "html"
            });
            request.done(function(msg) {
                $("#response").html(msg);
            });
            request.fail(function(jqXHR, textStatus) {
                alert( "Request failed: " + textStatus );
            });
        }
</script>
</head>
<body>
<div id="formulier">
<form method="" action="" name="form" id="form">
    <label for="brand">Brand</label>
    <select id="brand" name="brand">
        <option value="" >- Select -</option>
        <option value="1">Marlboro (1)</option>
        <option value="2">Pall Mall (2)</option>
    </select>
    <input type="button" value="submit" onclick="myCall();">
</form>
</div>
<div id="response">
</div>

这是我的php文件(process.php):

<?php
session_start();
$brand = $_POST['brand'];
if( $brand == '1'){
    echo "Value is 1";
}
else{
    echo "Value is: ".$brand;
}
?>

我在您的脚本中看到了几个问题:

  • 在任何时候都不能引用表单中的实际字段
  • 我宁愿将处理程序放在ajax调用中

试试这个:

    function myCall(){
        var request = $.ajax({
            url: "process.php",
            type: "post",
            dataType: "html",
            data: $('#form').serialize(), //here you send the form fields
            success: function(msg) {
                $("#response").html(msg);
            }, 
            error: function(jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            }
         }
    }

您应该使用json_encode(http://us1.php.net/json_encode)用于在CCD_ 2中进行响应。

确保您设置了会话变量,并在稍后读取它(在php-else块中),例如。,$_SESSION["brand"] = "2";

您应该尝试定义表单属性

<form method="POST" action="" name="form" id="form">