php的jQuery变量不起作用


jQuery variable to php not working

我需要将jQuery变量传递给PHP变量,所以我制作了简单的代码进行测试,但它不起作用。

这只是一个测试文件。最后,我必须做一些更高级的事情,但我无法做到!

我有3个文件

在character.html中,我有:

    <a href="character-save.php" class="saved">SAVE</a>

在character.js中(它是character.html的外部javascript)

    $(document).ready(function() {
    $('.saved').click( function () {
    var avatarID = 123;
    $ajax({
    url :'character-save.php',
    data:{"avatarID":avatarID},
    type: 'post',
    dataType: 'json',
    });
    });
    });

在character-save.php中,我尝试这个:

    <?php
    header('Content-type: application/json');
    $result = $_POST['avatarID'];
    $result = htmlentities($result, UTF-8);
    echo json_encode($result);
    exit();
    ?>

而且它不会打印123

在php文件中,您有一个UTF-8的mistaks,它应该包含在括号中。

<?php
   header('Content-type: application/json');
   $result = $_POST['avatarID'];
   $result = htmlentities($result, 'UTF-8');  // It should be 'UTF-8'
   echo json_encode($result);
   exit();
?>

您的语法错误--不是$ajax而是$.ajax--不要忘记.点。

此外,您还需要某种方法来检查响应,因此可以通过添加ajax回调和必要的jquery来更新html,也可以使用alert或日志响应到控制台。像这样的事情应该会给你一个很好的指示。

$.ajax({
    url :'character-save.php',
    data:{"avatarID":avatarID},
    type: 'post',
    dataType: 'json'
}).done(function(response) {
    alert(response.data);
});

在您的PHP中,将$result = htmlentities($result, UTF-8);更改为$result = htmlentities($result);还可以通过将结果放入数组来验证json,然后将该数组编码为json,并像这样回显:

<?php
header('Content-type: application/json');
$result = $_POST['avatarID'];
$result = htmlentities($result);
$return["data"] = $result;
echo json_encode($return);
exit();
?>

在您的javascript中,您必须添加e.preventDefault()以防止页面重定向到character save.php

在点击功能中添加e

请参阅下面更新的javascript部分

$(document).ready(function() {
$('.saved').click( function (e) {
    e.preventDefault();
    var avatarID = 123;
    $.ajax({
        url :'character-save.php',
        data:{"avatarID":avatarID},
        type: 'post',
        dataType: 'json',
        success: function(msg){
            alert(msg);
        }
    });
});

});

试试这个,

$(document).ready(function() {
$('.saved').click( function () {
  var avatarID = 123;
  $ajax({
    type:"POST",
    url: 'character-save.php&avatarID='+avatarID ,
    success:function(response){
       alert(response);
    });
});
});

在character-save.php中尝试以下操作:

 <?php  echo $_GET['avatarID'];
 ?>