需要帮助使用AJAX将PHP变量传递给jQuery

时间:2021-12-27 23:15:42

I have a variable in the PHP code called $final_value. I am trying to pass it into a jQuery file using $.ajax but I am unable to do so. Any help will be appreciated.

我在PHP代码中有一个名为$ final_value的变量。我试图使用$ .ajax将其传递到jQuery文件,但我无法这样做。任何帮助将不胜感激。

HTML (test.php)

<body>
    <h1>Test</h1>
    <p class="result">
    <?php            
        $final_value = 27.00;            
        echo '<strong>'.$final_value.'</strong>';
        echo json_encode($final_value);
    ?>
    </p>
    <p id="test"></p>        
</body>

jQuery

$(document).ready(function(){
    createValue();

    function createValue(){        
    $.ajax({
        url: 'http://localhost/test.php',
        method: 'post',            
        dataType: 'json',
        success: function(output){
            $('#test').append(output);
        },
        error: function(){
            alert('error');
        }
    });
    }
});

1 个解决方案

#1


Your PHP script returns HTML, not JSON. So use dataType: 'html' in the AJAX call. But you shouldn't have <body> around the HTML -- it's going to get inserted into a DIV that's already in the body, and you can't have multiple <body> tags in the same document.

您的PHP脚本返回HTML,而不是JSON。所以在AJAX调用中使用dataType:'html'。但是你不应该在HTML周围有 - 它会被插入到已经存在于主体中的DIV中,并且你不能在同一个文档中有多个标签。

You can get rid of echo json_encode($final_value); in the PHP, it's not needed.

你可以摆脱echo json_encode($ final_value);在PHP中,它不是必需的。

Or change the PHP so it only echoes the JSON -- get rid of all the HTML around it. Then your jQuery code will need to wrap the response into HTML and add it to the DOM:

或者更改PHP以便它只回显JSON - 摆脱它周围的所有HTML。然后你的jQuery代码需要将响应包装成HTML并将其添加到DOM:

$.ajax({
    url: 'http://localhost/test.php',
    method: 'post',            
    dataType: 'json',
    success: function(output){
        $('#test').append("<strong>" + output + "</strong>");
    },
    error: function(){
        alert('error');
    }
});

#1


Your PHP script returns HTML, not JSON. So use dataType: 'html' in the AJAX call. But you shouldn't have <body> around the HTML -- it's going to get inserted into a DIV that's already in the body, and you can't have multiple <body> tags in the same document.

您的PHP脚本返回HTML,而不是JSON。所以在AJAX调用中使用dataType:'html'。但是你不应该在HTML周围有 - 它会被插入到已经存在于主体中的DIV中,并且你不能在同一个文档中有多个标签。

You can get rid of echo json_encode($final_value); in the PHP, it's not needed.

你可以摆脱echo json_encode($ final_value);在PHP中,它不是必需的。

Or change the PHP so it only echoes the JSON -- get rid of all the HTML around it. Then your jQuery code will need to wrap the response into HTML and add it to the DOM:

或者更改PHP以便它只回显JSON - 摆脱它周围的所有HTML。然后你的jQuery代码需要将响应包装成HTML并将其添加到DOM:

$.ajax({
    url: 'http://localhost/test.php',
    method: 'post',            
    dataType: 'json',
    success: function(output){
        $('#test').append("<strong>" + output + "</strong>");
    },
    error: function(){
        alert('error');
    }
});