【问题标题】:PHP session variable not passed while processing with AJAX使用 AJAX 处理时未传递 PHP 会话变量
【发布时间】:2013-12-01 23:24:43
【问题描述】:

我正在编写一个脚本,该脚本根据所选值回显答案。稍后这将是多个值,但现在我只是在测试。 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;
}
?>

【问题讨论】:

  • 我没有看到对$_SESSION 的任何引用?假设您只是在这里谈论发布数据...
  • 在您的 jQuery ajax 请求中,我没有看到任何正在发送的数据。你指定了一个数据类型,但从未说过要发送什么。

标签: php jquery ajax session variables


【解决方案1】:

我在您的脚本中发现了几个问题:

  • 您绝不会引用表单的实际字段
  • 我宁愿将处理程序放在 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);
            }
         }
    }

【讨论】:

  • 这修复了它,我一直在努力使用“数据”,找不到合适的方法将其放入代码中,所以我把它忽略了。我刚刚开始研究 jQuery 和 ajax,今天学到了一些东西。谢谢!
【解决方案2】:

您应该使用json_encode (http://us1.php.net/json_encode) 回复process.php

【讨论】:

  • 这是向前迈出的一步。现在它仍然在选择值“1”时返回我的“else”语句,它应该回显“Value is 1”,而 else 语句说 Value is: null 所以显然我的帖子值为 null 而它应该是 1 或 2...
【解决方案3】:

确保您设置了session variable 并稍后阅读(在您的 php else 块中),例如, $_SESSION["brand"] = "2";

【讨论】:

    【解决方案4】:

    你应该尝试定义表单属性

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 2021-01-07
      • 2013-05-01
      • 2013-08-11
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      相关资源
      最近更新 更多