I just set up a jquery post that parses the result. I keep JSON.parse: unexpected character at line 1 column 2 of the JSON data app.js:31:24
Not sure why this isn't working. I currently have the /api/word
endpoint returning the result if it exists on the post, if not it returns a queue id that is then polled to the same endpoint with a GET
that returns false until the result is available.
here is my app.js
(function () {
'use strict';
var configOptions = {
endpoint : '/api/word'
};
jQuery(document).ready(run);
function run() {
jQuery('form').on('submit', submitForm);
}
function submitForm(e) {
e.preventDefault();
var data = jQuery(e.currentTarget).serialize();
jQuery('button').prop('disabled', true);
jQuery.ajax({
url: configOptions.endpoint,
method: 'POST',
data: data,
success: readQueueResults,
error: showError
});
function readQueueResults(response) {
console.log(response);
var data = jQuery.parseJSON(response);
var interval = setInterval(function () {
jQuery.ajax({
url: configOptions.endpoint,
method: 'GET',
data: 'id=' + data.id,
success: showResults
});
}, 500);
function showResults(response) {
if (response) {
clearInterval(interval);
jQuery('button').prop('disabled', false);
var data = jQuery.parseJSON(response);
renderMessage('alert-success', 'Your word is <b>' + data.percent + '%</b> pronounceable');
}
}
}
function showError(error) {
console.warn(error.status, error.statusText);
jQuery('button').prop('disabled', false);
renderMessage('alert-danger', '<b>' + error.status + '</b> - ' + error.statusText);
}
}
function renderMessage(classes, message) {
jQuery('.alert').remove();
var div = jQuery('<div>', {class: 'alert clear text-center row ' + classes});
div.append(message);
div.appendTo('.col-md-6');
}
}());
the console log is either
18828f7e-5554-43ee-8d3c-b00abe1409ca
or
Object {pronounceability: "0.0"}
Most likely JSON is malformed. Remember, that JSON notation is only a subset of JavaScript object syntax. For example, if you forget to put keys inside of double quotes, parser will reject such object. Please post the JSON that you try to parse.
You can also check if your JSON is valid with one of many online JSON validation tools like this one: http://jsonlint.com/
EDIT (after console.log is posted): it looks like the problem is on the serverside, neither of two console outputs is a valid JSON string.
From the log it seems both returned types are not well formed JSON, the result shall be a string in well formed JSON for the jQuery.parseJSON
to properly parse it.
Making a checking is beneficial as follows:
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
由于我使用的是Flask
它已经发送回一个已解析的对象,所以我不得不取出jQuery.parseJSON(response)
来修复它
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.