我是jquery的菜鸟,我被困在这个ajax请求上。我的本地网络上有一台运行python服务的服务器。当我通过带有请求的浏览器点击服务器时
http://192.168.0.109:5000/api/environment?seconds=10
我得到了我希望在浏览器中显示的JSON。所以我知道服务器工作正常并响应请求确定
{
"Bedroom Light": {
"host": "192.168.0.121",
"model": "Belkin Plugin Socket 1.0",
"name": "Bedroom Light",
"serialnumber": "221323K1300027",
"state": 0,
"type": "LightSwitch"
}
但是,当尝试通过Jquery执行此操作时 - 我得到一个jQuery - SyntaxError:意外的令牌:浏览器控制台中的错误。 这是我的Jquery
$(function () {
$.ajax({
url: 'http://192.168.0.109:5000/api/environment?seconds=10',
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function(data) {
console.log('sucess',data);
}
});
});
我正在通过main.js
运行下一页<!doctype html>
<html><head>
<meta charset="utf-8">
<title>Home - Dashboard</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
</body>
</html>
我试过了
dataType: 'json',
而不是jsonp,仍然会遇到此问题。 我在此网站上的另一篇文章后添加了crossdomain:true,但仍然收到错误。
我在哪里错了?
我的服务器在运行ajax时在控制台中记录以下内容
192.168.0.149 - - [2017-01-07 10:25:53] "GET /api/environment?seconds=10&callback=jQuery11110725321438557059_1483745153757&_=1483745153758 HTTP/1.1" 200 3977 0.510238
当我直接通过浏览器点击它时,它会记录下来。
192.168.0.149 - - [2017-01-07 10:27:02] "GET /api/environment?seconds=10 HTTP/1.1" 200 3977 0.629556
我的网络服务器和运行python服务的服务器都位于同一网络/子网上。
btw:python服务是http://ouimeaux.readthedocs.io/en/latest/readme.html
提前致谢
答案 0 :(得分:0)
您的输出不是有效的json,它应该是对象或对象的数组。你的输出json缺少“}”。
{
"Bedroom Light": {
"host": "192.168.0.121",
"model": "Belkin Plugin Socket 1.0",
"name": "Bedroom Light",
"serialnumber": "221323K1300027",
"state": 0,
"type": "LightSwitch"}
}
答案 1 :(得分:0)
您告诉jQuery请求JSONP:
dataType: 'json',
但服务器正在发回JSON,而不是JSONP。 JSON无效JSONP,因此您会收到该错误。
你可以
enable CORS(在服务上)告诉jQuery期待JSON:
---
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tables)
library(dplyr)
```
```{r table, results='asis'}
seed <- 1
iris2 <- iris %>% mutate(Region = factor(sample(c('East', 'West', 'Central'), 150, replace = TRUE)))
tabular((Species + 1) ~ (Region + 1) * Sepal.Length * Paste(Percent(), length, sep = '\\% (', postfix = ')'),
data = iris2) %>%
latex %>%
print
```
答案 2 :(得分:-1)
JSON.stringify(data)
。这将把它变成处理它的请求的正确格式
答案 3 :(得分:-1)
尝试这个..
.ajax({
method: "GET",
url: "http://192.168.0.109:5000/api/environment?seconds=10",
dataType: "jsonp"
}).done(function(data) {
console.log('sucess',data);
});