如何在php代码中获取JS变量值而不在url中传递它

时间:2018-07-18 11:00:40

标签: javascript php jquery

我正在使用此js代码进行ajax请求并获取数据,此代码效果很好,并在文本框中显示了数据。但是由于某些原因,我想将js变量id1的值转换为php代码(index.php)。我试过了,但是无法将id1的值输入到php代码中,请帮助。

HTML代码:(index.php)

<body>
  <input type="text" name="urn_no" ID="urn_no" value=""/>
  <input type="number" name="mob_1" ID='mob_1' value="" onkeydown="getData(this.value);" />
 </body>

JS代码:(index.php中的代码)

function getData(val) {
  $.ajax({
    type: "POST",
    url: "test.php",
    dataType: "json",
    data:'dt='+val,
    success: function(data){
      var len = data.length;
      if(len > 0){
        var id1 = data[0]['id1'];
        // Set value to textboxes
        document.getElementById('urn_no').value = id1;
      }
    }
  });
}

PHP CODE(test.php)

<?php
if (! empty($_POST["dt"])) {
  $sql="SELECT * FROM call_data WHERE U_no = '".$_POST["dt"]."'";
  $result = mysqli_query($con,$sql);
  if(!$result || mysqli_num_rows($result)<=0) {

  } 
  $users_arr = array();
  while( $row = mysqli_fetch_array($result) ) {
    $r1=$row['URN_Number'];
    $users_arr[] = array("id1" => $r1);
  }
  echo json_encode($users_arr);
  exit;
}
?>

1 个答案:

答案 0 :(得分:-1)

这是一种在用户键入时继续加载相关数据的方法:

<?php

$mob_1 = filter_input(INPUT_GET, 'mob_1');

// if we're responding to an AJAX call, send back HTML fragment
if ($mob_1) {
    $sql = "SELECT URN_Number FROM call_data WHERE U_no = $mob_1 LIMIT 1";
    $result = mysqli_query($con, $sql);
    if (!$result || mysqli_num_rows($result) <= 0) {
        echo "Nothing found";
        exit();
    }
    $URN = mysqli_fetch_array($result)['URN_Number'];
    echo "<p>Here's some content related to URN $URN</p>";
    exit();
}

// if not, send back main document
?><!doctype html>
<html>
    <head>
        <title>URN Lookup</title>
        <meta charset="utf-8">
    </head>
    <body>
        <input type="number" id="mob_1" />
        <div id="result"></div>
        <script>
            $('#mob_1').on('keyup', function () {
                // load HTML fragment
                $('#result').load("index.php?mob_1=" + $(this).val());
            });
        </script>
    </body>
</html>