douyeyan0650 2019-04-05 02:23
浏览 171

使用php从数据库中获取带引号或撇号的字符串,使用json_encode,然后尝试在javascript中解析JSON

I have a table full of strings in a database, about a sentence long each. Some have quotation marks in them or apostrophes. I run a fetch in React-native, which runs a php file. This php file gets a random item from the table and echos it so the javascript can parse the JSON string and do things with it. If the string has quotation marks or apostrophe(s), the app crashes with "JSON parse error: unexpected EOF". I have tried addslashes() and I have even tried using the php function str_replace() to replace quotations and apostrophes with obscure characters. Either way, I still get the crash and the same error message. Here is part of the code here:

$get_fate = "SELECT * FROM $fates ORDER BY RAND() LIMIT 1";
$run_fate = mysqli_query($con, $get_fate);
$num_fates = mysqli_num_rows($run_fate);
if ($num_fates == 1) {
    $row_fate = mysqli_fetch_assoc($run_fate);
    $fate = $row_fate['fate'];

    $msg = addslashes($fate);
    $msg_json = json_encode($msg);
    echo $msg_json;
} else ...

And the javascript side:

getFate = async () => {
    let user = await AsyncStorage.getItem('email');

    fetch('fetch address goes here', {
        method: 'POST',
        headers: {
        'Accept': 'application/json',
        'Content-Type': 'application.json',
        },
        body: JSON.stringify({
            email: user
        })
    }).then((response) => response.json())
    .then((responseJson) => {
        this.setState({fate: responseJson});
    }).catch((error) => {
        console.error(error);
    });
}

Here is an image of the crash:

enter image description here

And if it means anything, I was sent a big word file of all these "fates". I used fates.splitlines() in python to separate them all into separate strings and put them into an array, which I looped through in php and inserted into the database. I then noticed there was some kind of klingon looking text where quotes and apostrophes should be, so I "fixed" that with the following SQL queries:

UPDATE choose_your_fate SET fate = REPLACE(fate, '“', '“');
UPDATE choose_your_fate SET fate = REPLACE(fate, 'â€', '”');
UPDATE choose_your_fate SET fate = REPLACE(fate, '’', '’');
UPDATE choose_your_fate SET fate = REPLACE(fate, '‘', '‘');

</div>
  • 写回答

2条回答 默认 最新

  • doru52911 2019-04-05 08:36
    关注

    The first thing to do is to add a header to your PHP of Content Type (application/json).

    header('Content-Type: application/json');
    

    Next, it's probably your JSON is ill-formed. Instead of using

    response.json() 
    

    trying using

    response.text()
    

    this should return the String from the server.

    It could be that you have an error message in your PHP which is coming back in the response, or illformed JSON.

    As a general point of refactor. Consider using try catches in your code, so you don't crash the app when you encounter a non-show stopper like this.

    Like:

    getFate = async () => {
        let user = await AsyncStorage.getItem('email');
    
        fetch('fetch address goes here', {
            method: 'POST',
            headers: {
            'Accept': 'application/json',
            'Content-Type': 'application.json',
            },
            body: JSON.stringify({
                email: user
            })
        }).then((response) => response.text())
        .then((responseTxt) => {
            //Console log out the response, so you can see the response
            console.log(responseTxt);
        }).catch((error) => {
            console.error(error);
        });
    }
    

    The OP has stated the response from the server is incorrect.

    It seems special characters are breaking your response. Can you use the QUOTE function in MySQL?

    https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_quote

    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程