php json_encode 不使用 html 字符串作为值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9764598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:35:45  来源:igfitidea点击:

json_encode not working with a html string as value

phpjqueryajaxjson

提问by planet x

I am debugging this ajax for quite a time now. I have this on my jQUery file:

我调试这个 ajax 已经有一段时间了。我的 jQUEry 文件中有这个:

$("#typeForm").ajaxForm({
    success : function(html){
        alert(html);
}).submit();

This calls service.php, and within it I have this:

这称为service.php,其中我有这个:

$data = array('upload_data' => $this->upload->data());
$str = "<div style='position:relative'><img src='/assets/ui/success.png' /><span style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>";
echo json_encode(array('file_name' => $data['upload_data']['file_name'], 'prompt' => $str));

This won't work. But by replacing $strto $str = "HELLO WORLD";the jQuery alerts what should I expected. What seems to be the problem?

这行不通。但通过更换$str$str = "HELLO WORLD";了jQuery提醒我所期待的应该。似乎是什么问题?

EDIT:

编辑:

Here is a screenie of the output:

这是输出的屏幕:

enter image description here

在此处输入图片说明

It does alerts, but if I modify my jQuery into this:

它会发出警报,但是如果我将 jQuery 修改为:

$("#typeForm").ajaxForm({
    success : function(html){
        var obj = $.parseJSON(html);
        alert(obj);
}).submit();

Then it does nothing at all, even alerting.

然后它什么也不做,甚至发出警报。

I did a var_dump on the json_encodeand here is the dump, it looks like a malformed JSON:

我做了一个 var_dump json_encode,这里是转储,它看起来像一个格式错误的 JSON:

string(214) "{"file_name":"cde595988d386529909ce5a8fe3a6d6f.png","prompt":"<div style="position:relative;"><img src="\/assets\/ui\/success.png" \=""><span style="position:relative;top:-15px;">Nachricht empfangen!&lt;\/span&gt;&lt;\/div&gt;"}"
</span></div>

Here is the full content of service.php

这里是service.php的全部内容

class Service extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
    public function index()
    {
        $filename = 'uploadfile';

        $config['upload_path'] = './uploads/temp';
        $config['allowed_types'] = 'jpg|png|gif|doc|docx|pdf|ppt|pptx|xls|xlsx|bmp';
        $config['max_size'] = '3072';
        $config['encrypt_name'] = TRUE;
        $config['remove_spaces'] = TRUE;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload($filename))
        {
            $error = array('error' => $this->upload->display_errors());
                    echo json_encode(array('error' => $error['error']));
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());
            $file_name = $data['upload_data']['file_name'];
            //print_r($data);
            //echo json_encode(array('test' => "Hello World"));
            $str = "<div style='position:relative;'><img src='/assets/ui/success.png' /><span style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>";
            $str2 = json_encode(array("file_name" => $file_name, "prompt" => $str));
            //var_dump($str2);
            exit(json_encode(array('file_name' => $data['upload_data']['file_name'], 'prompt' => $str)));
        }
    }
}

回答by Abhishek Sachan

I was having same problem with json_encodetoday. But after testing a lot I found the correct solution:

json_encode今天遇到了同样的问题。但经过大量测试后,我找到了正确的解决方案:

In PHP to encode the array or string:

在 PHP 中对数组或字符串进行编码:

json_encode($array, JSON_HEX_QUOT | JSON_HEX_TAG);

In JS to decode the same:

在JS中解码相同:

var d = $.parseJSON(content);

回答by Andreas Wong

Some stuff to try:

一些尝试的东西:

ajaxForm supports dataType argument, if you expect a JSON coming from the server, use dataType: jsonlike so

ajaxForm 支持 dataType 参数,如果您希望来自服务器的 JSON,请dataType: json像这样使用

$("#typeForm").ajaxForm({
    success : function(html){
       // html here is already automatically a json object
       alert(html.prompt);
    },
    dataType: 'json'
}).submit();

Could you post the full service.php? OR try the following:

你能发布完整的service.php吗?或尝试以下操作:

exit(json_encode(array('file_name' => $data['upload_data']['file_name'], 'prompt' => $str)));

exit(json_encode(array('file_name' => $data['upload_data']['file_name'], 'prompt' => $str)));

-- EDIT --

- 编辑 -

Not sure why json_encode returns such weird string :s, is the json_encodea standard php library or an external library? I'm asking this because some servers don't have json_encode in their php installation... I tested on my local and using php internal json_encode and it works fine:

不知道为什么 json_encode 返回如此奇怪的字符串:s,是json_encode标准的 php 库还是外部库?我问这个是因为有些服务器在他们的 php 安装中没有 json_encode ......我在我的本地测试并使用 php 内部 json_encode 并且它工作正常:

<?php
$str = "<div style='position:relative'><img src='/assets/ui/success.png' /><span style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>";
echo json_encode(array('prompt' => $str));

// output
//{"prompt":"<div style='position:relative'><img src='\/assets\/ui\/success.png' \/><span style='position:relative;top:-15px;'>Nachricht empfangen!<\/span><\/div>"}

回答by Andrew

How about convert all the potential problem characters instead of just what fixes the problem in this circumstance:

在这种情况下,如何转换所有潜在的问题字符,而不仅仅是解决问题的字符:

die(json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE));

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/function.json-encode.php

http://php.net/manual/en/json.constants.php

http://php.net/manual/en/json.constants.php

回答by Mohammad Fathi MiMFa

You should call only promptobject of your array not all! like below:

您应该只调用prompt数组的对象而不是全部!像下面这样:

$("#typeForm").ajaxForm({
    success : function(html){
        var obj = $.parseJSON(html);
        alert(obj.prompt);
}).submit(); 

回答by jerjer

If you cannot find a better solution for this you can encode the value to base64 encoding:

如果您找不到更好的解决方案,您可以将值编码为 base64 编码:

$data = array('upload_data' => $this->upload->data());
$str = base64_encode("<div style='position:relative'><img src='/assets/ui/success.png' /><span style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>");
echo json_encode(array('file_name' => $data['upload_data']['file_name'], 'prompt' => $str));

and in the client decode it, IMO this is more safer this is also more applicable if you're processing characters from different languages.

并且在客户端解码它时,IMO 这更安全,如果您正在处理来自不同语言的字符,这也更适用。

ALSO:

还:

to sure that no other characters will be added on the json string call exit;writer after you print it.

确保不会在 json 字符串调用出口上添加其他字符打印后的作家。

回答by Kuba Paczyński

JSON doesn't play well with stringoutput that comes out of magic method __toString()- it nearly impossible to json_encode()anything that even remotely touched something like this.

JSON 不能很好地处理string来自魔法方法的输出__toString()- 几乎不可能对json_encode()任何甚至远程触及这样的东西的东西。

<?php
/**
 * DEBUGGING NIGHTMARE
 * SO MUCH FUN, 10/10,
 */
class Nightmare {
  protected $str;
  public function __construct($str) {
    $this->str = $str;
  }
  public function __toString() {
    return $this->str;
  }
}

$test = new Nightmare('Hello Friends.');
echo $test;
> Hello Friends.

// cooool, so let's JSON the hell out of it, EASY

echo json_encode(['our_hello' => $test]);
// This what you expect to get, right?
> {"our_hello":"Hello Friends."}

// HAHA NO!!!
// THIS IS WHAT YOU GET:
> {"our_hello":{}}


// and this is why is that:

var_dump($test);
object(Nightmare)#1 (1) {
  ["str":protected]=>
  string(14) "Hello Friends."
}

print_r($test);
Nightmare Object
(
    [str:protected] => Hello Friends.
)

回答by AlfredoVR

string(214) "{"file_name":"cde595988d386529909ce5a8fe3a6d6f.png","prompt":"<div style="position:relative;"><img src="\/assets\/ui\/success.png" \=""><span style="position:relative;top:-15px;">Nachricht empfangen!&lt;\/span&gt;&lt;\/div&gt;"}"
</span></div>

This seems to be broken because there's no quote escaping. When an unescaped " is found, it breaks the JSON structure you expect. Escaped " should be \", single quotes with \' and so on.

这似乎被打破了,因为没有引用转义。当找到未转义的 " 时,它会破坏您期望的 JSON 结构。转义的 " 应该是 \",单引号和 \' 等。

回答by davehale23

It looks like you need to escape your quotes server-side. Since they are in there, it seems to be creating an invalid JSON string.

看起来您需要在服务器端转义报价。由于它们在那里,它似乎正在创建一个无效的 JSON 字符串。