是我的同源策略的代码受害者?
-
27-09-2019 - |
题
下面是我的代码。你必须看看亲切它从这种形状“同源策略”受到影响。对于HTML域名(http://127.0.0.1/jqload.html)PHP文件(http://127.0.0.1/conn_sql.php)。这是JSON格式:[{ “选项”: “smart_exp”},{ “选项”: “user_int”},{ “选项”: “blahblah”}] 其实我是想将数据追加JSON,我收到HTYML与用户输入与我在受苦。如果我使用eval解析,它工作正常,在这里指出其认沽。但是,如果使用JSON.parse来解析,整个代码将停止工作与此发布错误消息“‘重要提示:在部署之前取下json2.js这条线’。我把我的代码的其它一些问题上的计算器论坛&我被告知,我的代码,导致在追加JSON数据的问题“同源策略”受到影响。所以,你能请尽快就我的代码,从这一政策受苦?虽然我怀疑它从政策受到我得知,如果文件驻留在不同的域限,这里既有文件驻留彼此相邻。
代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input>
<p><input type = "button" id = "send" name = "send" value = "send" onClick=
"ADDLISTITEM"></input>
<p><select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{
alert (json.length); // working
alert json.options[1]; // do not show any value, message just for testing
json.options[json.length+1] = 'newOption'; //not working; HELP HERE
jsonString = JSON.stringify(json);//working fine for current data
alert(jsonString);
//here I have to implement send this stringify(json) back to server,HELP
//HERE
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>
</body>
</html>
解决方案
<击>你是在正确的轨道上,但在这里:$.each(jsonData, function (i, j) { ... }
你实际上是通过jsonData
字符串的每个字符,而不是json
对象循环。只要改变jsonData到JSON的$.each()
里面,它应该正常工作(无论你使用eval或JSON.parse,但我建议后者)。行使>
编辑:由于您使用jQuery.getJSON()
,你不需要使用eval
或JSON.parse
- jQuery不会给你。所以,你的回调函数内,只需设置json = jsonData
。
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = jsonData;
$.each(json, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});
});
});
</script>
不隶属于 StackOverflow