0

我正在尝试使用 AJAX 将变量从 jquery 传递到 php,反之亦然,但就是做不到!我已经查看了许多类似的问题和示例,但仍在为同一个问题而苦苦挣扎。

这是我尝试将变量传递给 php 的部分。

在 main.js 中:

$(document).ready(function(){
  doSearch();
});

function doSearch(){
  var inID = $('#inID').val();
  var memInd = $('#memInd').val();
  var t1 = $('#t1').val();
  var t2 = $('#t2').val();
  alert("ID: "+inID+"memIND: "+memInd);
  $.ajax({
    type: "POST",
    url: "index.php",
    data: { inID: inID, memInd: memInd , t1: t1, t2: t2} 
  });
}

索引.php:

$inID = $_POST["inID"];
echo $inID
4

4 回答 4

0

You are missing the quotes,

data: { "inID": inID, "memInd": memInd , "t1": t1, "t2": t2}
于 2013-08-02T12:16:13.877 回答
0

Change dataType: "HTML" to dataType: "json" and let me know if it works :) (or just delete that line entirely as $.ajax autodetects)

Additionally, $.post() has a shorter syntax than $.ajax if you're not doing anything fancy, so you could just use the following

$.post("index.php", { inID: inID, memInd: memInd , t1: t1, t2: t2});

And while you're at it, it's good practice to quote your params as Sudip Pal mentions, but not necessary if your parameter name is strictly alphanumeric..

Debugging Round 1

Change the doSearch() Javascript function to the following:

function doSearch(){
    var inID = "inIdValue";
    var memInd = "memIndVal";
    var t1 = "t1Val";
    var t2 = "t2Val";
    alert("ID: "+inID+"memIND: "+memInd);
    $.post("index.php",
        {
            inID: inID, memInd: memInd , t1: t1, t2: t2
        },
        function(data) {
            $('body').html(data);
            $('body').append('<button onclick="doSearch()">Reload</button>');
        }
    );
}

Backup the file as index2.php, then delete everything inside index.php and replace it all with the following (just copy and paste):

<?php
echo "<pre>";
print_r($_POST);
die("</pre>");
?>

Then please paste the results :)

于 2013-08-02T12:16:21.197 回答
0

问题是我将运行 ajax 函数的 .js 包含在同一个 php 页面中,该页面正在接收($_POST)来自 UI 输入的值。在我制作了一个单独的 search.php-page 来接收这些值之后,一切正常。我还最终使用了 jquery post() 的较短语法

        $.post('search.php',{id:id, mem:mem, t1:t1, t2:t2},function(res){
            $("#result").html(res);
        });
于 2013-08-09T06:32:09.893 回答
0

尝试这个

脚本 :

$.ajax({
          type: "POST",
          url: "index.php",
          dataType: "json",
          data: { inID: inID, memInd: memInd , t1: t1, t2: t2} ,
          success : function(res){
             alert(res.inID);
          }
       });

在 php 文件中

echo json_encode($_POST);

希望它会有所帮助

于 2013-08-02T12:21:53.503 回答