猿问

Ajax 将 javascript 变量发送到 php

我正在尝试将 JS 变量发送到 PHP 文件,但它似乎不起作用。在控制台中,它以文件形式显示错误show.php。我无法理解我做错了什么。


function details(id) {

  var id = id;

  //   alert(id);

  $.ajax({

    type: 'POST',

    url: 'show.php',

    data: id,

    success: function(data) {

      alert("hi");

    }

  });

}

<button onclick="details(<?php echo $id ; ?>)" class="btn btn-rounded btn-primary">Details</button> 

显示.php:


<?php 

  if (isset($_POST['id']))

  {

    $uid = $_POST['id'];

    echo json_encode($uid);

  }

?>


守候你守候我
浏览 109回答 2
2回答

冉冉说

在 json 对象中写入数据,请参见下面的代码function details(id)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var id = id;&nbsp; &nbsp; &nbsp;//&nbsp; &nbsp;alert(id);&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: 'show.php',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data:&nbsp; {id:id},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function(data)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert("hi");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp;

梦里花落0921

检查您的网络选项卡并检查发送参数列表。你不得不提到数据类型 json尝试这个function details(id)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var id = id;&nbsp; &nbsp; &nbsp;//&nbsp; &nbsp;alert(id);&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'POST',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: 'show.php',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: 'json',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data:&nbsp; {'id':id},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function(data)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert("hi");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp;在你的 show.php<?php&nbsp;&nbsp; if (isset($_POST['id']))&nbsp; {&nbsp; &nbsp; $uid = $_POST['id'];&nbsp; &nbsp; echo json_encode($uid);&nbsp; }?>
随时随地看视频慕课网APP
我要回答