尽管收到了响应,但JSON输入意外结束

时间:2017-10-23 14:17:15

标签: javascript html json

我已经编写了这个简短的代码,可以从网页上通过REST请求json文件:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <meta charset="utf-8" />
  <title></title>
 </head>
 <body>
  <button type="submit" onclick="UserAction()">Search</button>

  <script type="text/javascript" language="javascript">
  function UserAction() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", "http://date.jsontest.com/", true);
  xhttp.setRequestHeader("Content-type", "application/json");
  xhttp.send();
  var response = JSON.parse(xhttp.responseText);
  document.write(response);

  }
  </script>
 </body>
</html>

但是,在chrome的java脚本控制台中,我收到以下错误:

VM33:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at UserAction (HTMLPage1.html:17)
at HTMLButtonElement.onclick (HTMLPage1.html:9)

但是当我在控制台中检查网络响应时,我可以看到以下格式的响应是正确的,但它也没有显示在网页上:

{
   "time": "02:08:35 PM",
   "milliseconds_since_epoch": 1508767715990,
   "date": "10-23-2017"
}

我不知道是什么原因导致这个问题,有谁知道如何修复它?

2 个答案:

答案 0 :(得分:3)

xhttp.send();是异步的。这意味着当你执行JSON.parse(xhttp.responseText);时,响应中没有任何内容。您必须使用该活动......

xhttp.onreadystatechange = function() {//Call a function when the state changes.
    if(xhttp.readyState == 4 && xhttp.status == 200) {
        var response = JSON.parse(xhttp.responseText);
        document.write(response);
    }
}

答案 1 :(得分:-1)

首先使用JSON.stringify()将JavaScript对象转换为字符串。 然后使用JSON.parse

&#13;
&#13;
import tensorflow as tf
from tensorflow.contrib.distributions import Normal
import numpy as np
import matplotlib.pyplot as plt

DNA_SIZE = 1
POP_SIZE = 10
LR = 0.1
N_GENERATION = 50

def F(x):
    return x**2

def get_fitness(value):
    return -value

mean = tf.Variable(tf.constant(13.), dtype=tf.float32)
sigma = tf.Variable(tf.constant(5.), dtype=tf.float32)
N_dist = Normal(loc=mean, scale=sigma)
make_kids = N_dist.sample([POP_SIZE])

tfkids = tf.placeholder(tf.float32, [POP_SIZE, DNA_SIZE])
tfkids_fit = tf.placeholder(tf.float32, [POP_SIZE])
loss = -tf.reduce_mean(N_dist.log_prob(tfkids) * tfkids_fit)
train_op = tf.train.GradientDescentOptimizer(LR).minimize(loss)

x = np.linspace(-20, 20, 100)
plt.plot(x, F(x))

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

plt.ion()
for g in range(N_GENERATION):
    kids = sess.run(make_kids)
    kids_fit = get_fitness(F(kids))
    sess.run(train_op, feed_dict={tfkids: kids, tfkids_fit: kids_fit})

    if "plot_points" in globals():
        plot_points.remove()

    plot_points = plt.scatter(kids, F(kids), s=30)
    plt.pause(0.05)

plt.ioff()
plt.show()
&#13;
&#13;
&#13;