简体   繁体   English

成功的jquery $ .post()之后需要帮助返回json字符串

[英]Need help returning a json string after a successful jquery $.post()

I am posting to a php page that is returning the following json encoded string 我正在发布到返回以下json编码字符串的php页面

{"msg":"Hi {{full_name}}, <br \/>\r\n<br \/>\r\n  It was nice meeting you."}

I had added that json object in the <script> </script> 我在<script> </script>添加了json对象

However when run the $.post() and try to output data.msg it says undefined . 但是,当运行$.post()并尝试输出data.msg时,它显示为undefined

Here is the full code 这是完整的代码

  $.post("mass_messaging.php",{template_id: template_id})

        .done(function(data){

            console.log(data.msg)
            //Outputs undefined??? 


        });

Below is a snippet of my html code 以下是我的html代码段

<script>

addMustachePlaceHolder();

{"msg":"Hi {{full_name}}, <br \/>\r\n<br \/>\r\n  It was nice meeting you."}

</script>

Any help would be really appreciated. 任何帮助将非常感激。

You probably need to parse the json as it is a string and you need an object. 您可能需要解析json,因为它是一个字符串,并且需要一个对象。 jQuery can do that automatically if you set the data type: 如果您设置数据类型,jQuery可以自动执行此操作:

$.post("mass_messaging.php", {template_id: template_id}, function(){}, "json")
                                                                       ^^^^^^ here

Apart from that it is not entirely clear what you are returning. 除此之外,还不清楚您要返回什么。 You should only return one valid json string from your php script and nothing else; 您应该只从PHP脚本返回一个有效的json字符串,而不能返回其他任何内容; no script tags, javascript, etc. 没有脚本标签,JavaScript等。

I found the answer. 我找到了答案。 I was using json_encode() which was returning a json string. 我正在使用json_encode(),它返回一个json字符串。

So i just used data = JSON.parse(data); 所以我只是用data = JSON.parse(data);

and it worked! 而且有效!

Below is what I did 以下是我所做的

$.post("mass_messaging.php",{template_id: template_id}) $ .post(“ mass_messaging.php”,{template_id:template_id})

    .done(function(data){

       data = JSON.parse(data);

            console.log(data.msg);



    });
var obj = jQuery.parseJSON( data );
console.log(obj.msg);

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

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