Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

javascript - Why do I get error when trying to parse this json object?

I have the following PHP (Codeigniter Frameword) code:

$webpages = $this->webpageModel->select('webpageID,webpageTitle')->where('webpagecategoryID', $webpagecategoryID)->findAll();
header('Content-Type: application/json');
echo json_encode(array("response" => $webpages))

In the console, this is what is displayed:

{"response":[{"webpageID":"3","webpageTitle":"u03a7u03b1u03b9u03c1u03b5u03c4u03b9u03c3u03bcu03ccu03c2 u03b1u03c0u03cc u03c4u03bfu03bd u03c0u03c1u03ccu03b5u03b4u03c1u03bf"}]}

This is my JavaScript:

$(document).ready(function() {
        let category = $('#webpagecategoryID');
        let webpage = $('#webpageID');
        category.on('change', function(e) {
            webpage.empty();
            var req = new XMLHttpRequest();
            req.open("GET", "<?php echo base_url(); ?>/backEnd/Ticker/webpages_from_selected_category/" + category.val(), false);
            req.send();
            let res = JSON.parse(req.response);
            let response = res.response;
            let len = Object.keys(response).length;
            for (let i = 0; i < len; i++) {
                let titleLength = 150;
                var trimmedTitle = response[i]['webpageTitle'].substring(0, titleLength);
                webpage.append("<option value=" + response[i]['webpageID'] + ">" + trimmedTitle + "</option>");
            }
        });
    });

In the Javascript, when I try to parse the object, I get an error: Uncaught SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 1 of the JSON data

What I am doing wrong?

question from:https://stackoverflow.com/questions/65916255/why-do-i-get-error-when-trying-to-parse-this-json-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My problem has not been related with the JSON at all. I use CodeIgniter 4, which in the development environment post in the console the following tag:

<script type="text/javascript"  id="debugbar_loader" data-time="1611742634" src="http://ea3.test/index.php?debugbar"></script><script type="text/javascript"  id="debugbar_dynamic_script"></script><style type="text/css"  id="debugbar_dynamic_style"></style>

after my JSON. And after I switch the environment to production, this script tag is not displayed in the console, and my code works just fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...