JSON到JavaScript,SyntaxError:意外令牌& [英] JSON to JavaScript, SyntaxError: Unexpected token &
问题描述
我知道这个问题已经问过很多遍了,但是我真的不明白.
I know this question has been asked numerous times, but I really don´t get it.
我正在MVC中创建一个网站,并且正在从我的模型中创建一个JSON字符串.然后,我想将其作为参数传递给使用该函数绘制图形的JavaScript函数.
I am creating a site in MVC, and I'm creating a JSON string from my model. I then want to pass it as argument to a JavaScript function that uses it to plot a graph.
这是我创建JSON字符串的地方.这确实创建了有效的JSON字符串,我在 JSONLint 上进行了检查.
Here is were I create the JSON string. This indeed creates a valid JSON string, I checked it at JSONLint.
@{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var weightsAsJsonString = serializer.Serialize(Enumerable.Select(Model, weight =>
new
{
date = weight.Date,
value = weight.Value
}));
}
进一步,我从中创建一个JavaScript变量并将其传递给JavaScript函数:
Further down I create a JavaScript variable from it and pass it into the JavaScript function:
var jsonStringToGraph = @weightsAsJsonString;
google.setOnLoadCallback(drawVisualization(jsonstring));
运行此命令时,控制台将打印"SyntaxError:意外令牌&"我声明的是jsonStringToGraph
.我四处搜寻,得出结论,我应该在@weightsAsJsonString
旁加上'',所以我做到了.
When I run this, the console prints 'SyntaxError: Unexpected token &' at the line were I declare jsonStringToGraph
. I googled around and concluded that I should put ' ' around @weightsAsJsonString
, so I do that.
无论如何,在我的drawVisualization中,我这样做:
Anyway, in my drawVisualization, I do this:
function drawVisualization(teststring) {
.......
var parsedJson = JSON.parse(teststring);
这给了我SyntaxError: Unexpected token & Index:1
我知道底部的代码是导致异常的原因,但我不明白为什么.有人知道我在做什么错吗?
This gives me SyntaxError: Unexpected token & Index:1
I know that the code at the bottom is what is causing the exception, but I do not understand why. Do anyone understand what I am doing wrong?
这是weightsAsJsonString
This is the weightsAsJsonString
[{"date":"\/Date(1434492000000)\/","value":100.2},{"date":"\/Date(1434578400000)\/","value":99.2},{"date":"\/Date(1434664800000)\/","value":101.2},{"date":"\/Date(1434751200000)\/","value":98.2},{"date":"\/Date(1434837600000)\/","value":97.2},{"date":"\/Date(1434924000000)\/","value":96.2},{"date":"\/Date(1435010400000)\/","value":95.2},{"date":"\/Date(1435096800000)\/","value":94.2}]
推荐答案
听起来您的问题是试图通过Razor将内容注入JavaScript.默认情况下,@
将对您的内容进行HTML编码,这在JavaScript的上下文中无效.
It sounds like your issue is trying to inject content via Razor into JavaScript. By default @
will HTML-encode your content, which doesn't work in the context of JavaScript.
@Html.Raw(weightsAsJsonString)
将更好地工作,然后您的JS将具有一个JavaScript对象,因此以后不再需要JSON.parse
.
@Html.Raw(weightsAsJsonString)
will work better, and then your JS will have a JavaScript object, so there's no need for the JSON.parse
later on.
这篇关于JSON到JavaScript,SyntaxError:意外令牌&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!