试图将变量从$ .post传递给php

时间:2011-11-03 17:57:48

标签: php jquery .post

我有一个大文件(目前为止)应该是:

  • 从表单(jQuery)中的选择窗口小部件中获取变量
  • 异步提交表单(jQuery)
  • 使用从表单(php)
  • 中选择的变量从数据库返回记录

问题是,变量似乎永远不会到达php代码。

有人能告诉我我做错了吗?

我的代码:

(全部在一页上)

    <script type="text/javascript">
        $(function() {
        $("select").change(function () {
              var str = "";
        $("select option:selected").each(function () {
     str += $(this).text() + " ";
        });   
        $.post("index.php", { zip: str}, function(data){
        $('result').text(str); }, "json" );

    });//end select
    });//end function
    </script>

    <?php include_once ('../cons.php'); ?>
    <?php 
    if (isset($_POST['zip'])){
    $value = $_POST['zip'];   
    }else{
    $value = "nada";
    }
    echo $value;

    //I only get "nada"
    ?>
</head>

<body>

<div id="body">
<form id="findzip"><!-- jQuery will handle the form -->
<select name="zip">
<option value="">Find your zip code</option>
    <?php //use php to pull the zip codes from the database
    $mysqli_zip = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    if (mysqli_connect_errno()) {
            printf("Connect failed: %s", mysqli_connect_error());
            exit();
    }
    $q_zip = "select distinct(zip) from mc m group by zip";
    $r_zip = $mysqli_zip->query($q_zip);
    if ((!$r_zip) || ($r_zip == NULL)) {
            echo "no results ";
    }
    while($row_zip = $r_zip->fetch_array(MYSQLI_BOTH)) {
        echo "<option value='". addslashes($row_zip['zip']) . "'>" . addslashes($row_zip['zip']) . "</option>;\n";
    }//end while

    ?>
</select>
</form>
<!-- here's where the results go -->
<result></result>
<br/>
</div>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您编写的脚本会回显出类似“12345”的值。但是你的$ .post期望它是json类型。当我删除json类型时,它对我来说非常适合。

答案 1 :(得分:0)

尝试在其上添加ID,如下所示:

<select name="zip" id="zip">

然后从中获取值:

$("#zip").val();