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

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?