我有一个如下的ajax代码。现在我的php中的问题我只是写了一个echo作为代码,因为我的sql无法插入,我试着在这里进行比较,但我注意到它有额外的新行,如果(responseData ==“SMGFE \ n”,它会导致此语句失败) )。我甚至把额外的“\ n”放在一起检查,但它也失败了。该问题的任何解决方案?
function ajaxLoad(url,postData,plain) {
//alert("in url : "+url);
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType && plain) {
http_request.overrideMimeType('text/plain');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var responseData = http_request.responseText;
alert("http response :"+responseData+"TEST");
if(responseData=="SMGFE\n")
{
alert("Gname "+document.getElementById("gname").value+" Already Exist");
}
else{
alert("Successfully Inserted");
clearSelection();
window.opener.location.reload();
window.close();
}
}
else {
alert('Request Failed: ' + http_request.status);
}
}
};
//alert("before post data"+postData.length);
if (postData) { // POST
//alert("post data"+postData.length);
http_request.open('POST', url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.setRequestHeader("Content-length", postData.length);
http_request.send(postData);
}
else {
http_request.open('GET', url, true);
http_request.send(null);
}
}
答案 0 :(得分:1)
我不完全明白你想要做什么,但这不是解决你问题的方法吗?
if(responseData.substr(0,5) =="SMGFE")
答案 1 :(得分:1)
你最好尝试从你的php文件中删除来自responseData的换行符和任何空白区域试试
trim($your_php_variable_responseData);
请参阅php manual
> This function returns a string with whitespace stripped from the beginning
and end of str. Without the second parameter, trim() will strip these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
或者你可以试试javscript
responseData= responseData.replace(/^\s+|\s+$/g,"");