简体   繁体   English

如何从ajax调用返回数据到php

[英]how to return data from ajax call to php

i'm making an app which calls an JS function in php like 我正在制作一个在php中调用JS函数的应用程序

$data = "<script>JSFunction();</script>";

and JSFunction looks like this 和JSFunction看起来像这样

function JSFunction(){
$.ajax({
    type: 'POST',
    url:'url/to/file',
    data:{'text':"some text here"},
    success:function(response){
        res = JSON.parse(response);
        document.write(res.data);

    },
    error: function(err){
        console.log(err);
    }
});
}

and $data variable in php gets the expected results. php中的$data变量将获得预期的结果。 But when I echo $data; 但是当我echo $data; then data is printed on screen but browser page continues to reload. 然后数据打印在屏幕上,但浏览器页面继续重新加载。 (It don't reload actually, but that circle in browser tab continuously appears rotating). (它实际上并不会重新加载,但是浏览器选项卡中的圆圈会不断旋转)。 So how would I stop that reloading? 那么我将如何停止重新加载? or is there any other way to return data from ajax call except document.write() ? 还是除了document.write()以外,还有其他方法可以从ajax调用返回数据吗?

If you want to get JSON result from PHP script you may call ajax withe proper dataType : 如果要从PHP脚本获取JSON结果,可以使用适当的dataType调用ajax:

$.ajax({
        type: "POST",
        url: "url/to/script",
        dataType: 'json',
        success: function (data) {
            $.ajax({
                    type: "POST",
                    url: "url/to/php/script",
                    dataType: 'json',
                    data: {data: data},
                    success: function (data) {
                        // do something...
                    }
            })
        }
    })

Don't forget to encode $data in the PHP script using json_encode leading with the proper header: 不要忘了使用json_encode以正确的标头开头在PHP脚本中编码$ data:

header("Content-Type: application/json");
echo json_encode($data);

document.write is considered bad practice since it can overwrite your page. document.write被认为是不好的做法,因为它可能会覆盖您的页面。

Here is what you need to do: 这是您需要做的:

  1. Create an empty DIV with an id. 创建一个具有ID的空DIV。

  2. Use innerHTML to write the response to the DIV considering that your output is from trusted sources since innerHTML can output HTML and not only text . 考虑到您的输出来自受信任的源,请使用innerHTML编写对DIV的响应,因为innerHTML可以输出文本,而且可以输出HTML。

Your PHP: 您的PHP:

<div id ="x"></div>

<?php $data = "<script type='text/javascript'>JSFunction();</script>";
echo $data;
?>

Your JS: 您的JS:

function JSFunction(){
   reValue = document.getElementById("x");

   $.ajax({
   type: 'POST',
    url:'url/to/file',
    dataType:'json',
    data:{'text':"some text here"},
    success:function(response){
    x.innerHTML = response.data;

   },
    error: function(err){
    console.log(err);
   }
});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM