Javascript 拆分(错误?)
我尝试在冒号处拆分字符串并检查它是否成功。 api.php 给我返回一个 JSON。
$.ajax({
type: "POST",
url: "api.php",
data: { "somedata": "123"},
success: function (data, status, xhr) {
if (data.indexOf("text") != -1) {
var meinjson = $.parseJSON(data);
for (var key in meinjson) {
if (meinjson.hasOwnProperty(key) && key=="text") {
text = meinjson[key];
text = text.replace(/\+/g, " ");
text = decodeURIComponent(text);
if (text.indexOf(":") !== -1) {
text = text.split(/:(.+)?/);
var text1 = text[0];
var text2 = text[1];
}
if (text2 == undefined || text1 == undefined || text1 == void 0 || text2 == void 0 || text1=="" || text2=="") {
alert("fail");
}
}
}
}
}
});
我无法解释为什么 Internet Explorer 总是落入最后,但 Firefox 和 Chrome 却不然。 数据示例如下:
{"command":"SENDTEXT","text":"Lorem+Ipsum","command":"SENDTEXT","text":"Lorem+Ipsum+dolor","specialcommand":"CONNECTACCEPT"}
I try to split a string at the colon and to check whether it was successful.
The api.php gives me back a JSON.
$.ajax({
type: "POST",
url: "api.php",
data: { "somedata": "123"},
success: function (data, status, xhr) {
if (data.indexOf("text") != -1) {
var meinjson = $.parseJSON(data);
for (var key in meinjson) {
if (meinjson.hasOwnProperty(key) && key=="text") {
text = meinjson[key];
text = text.replace(/\+/g, " ");
text = decodeURIComponent(text);
if (text.indexOf(":") !== -1) {
text = text.split(/:(.+)?/);
var text1 = text[0];
var text2 = text[1];
}
if (text2 == undefined || text1 == undefined || text1 == void 0 || text2 == void 0 || text1=="" || text2=="") {
alert("fail");
}
}
}
}
}
});
I can not explain why the internet explorer to always fall into the last if but does not firefox and chrome.
A example of data is:
{"command":"SENDTEXT","text":"Lorem+Ipsum","command":"SENDTEXT","text":"Lorem+Ipsum+dolor","specialcommand":"CONNECTACCEPT"}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您缺少
}
。如果您在success
函数中的第一个if
之后缩进,您将看到位置。更新:
您以逗号分隔,但数据中“文本”的值不包含逗号。其中显示
"text":"Lorem+Ipsum"
的实际值为"Lorem+Ipsum"
,它不会包含"text":
。You're missing a
}
. If you indent after the firstif
in thesuccess
function you'll see where.Update:
Your are splitting on a comma, but the values of "text" in your data do not contain commas. Where it says
"text":"Lorem+Ipsum"
the actual value is"Lorem+Ipsum"
, it will not include"text":
.建议重构您的语句以利用错误检查。 Undefined 和 void 0 本质上是相同的。除了空字符串之外,它们都是假值。
Suggest refactoring your statement to leverage falsely checks. Undefined and void 0 are essentially the same. Along with empty string, they are all falsey values.