我有一个非常独特(而且非常深入)的问题。如果这两个特征中的任何一个对您没有吸引力,请不要认为需要继续阅读。
我有一个我从头开始编写的程序。它正在创建一个HTML页面,允许用户将数据插入该页面,然后提交该数据
提交后,数据写入我在本机上运行的node.js服务器。它唯一的工作就是传递传递给它的数据,并将其打印到启动它的控制台(在这种情况下为cmd提示)
它通过URL中的查询字符串写入,即http://localhost/?<parametersGoHere>
客户端文件(HTML页面,javascript程序)也使用名为http-server的node.js模块进行托管。链接到模块:https://github.com/nodeapps/http-server
(示例:进入存储所有文件的目录,并运行命令“http-server”托管localhost:8080
上的所有文件)
这是我的问题:当写入node.js服务器时,ajax调用每次都会失败 我可以在物理上写出包含带参数值的URL,服务器每次都会吐出正确的数据。
我在google chrome的开发者工具中看过这个,并且可以看到它在联系我列出的地址时遇到问题。但问题是,它与我手动输入并获得结果的网址完全相同。
话虽这么说,错误(在我看来)是在network.js文件中的某个地方。任何人都可以帮我找到这个错误吗?
服务器:(在命令提示符下在其目录中运行节点server.js)
var http = require('http');
var querystring = require('querystring');
var url = require('url');
var handler = function(request, response) {
var params = querystring.parse(url.parse(request.url).query);
var writeOut = function(status) {
response.writeHead(status, {'Content-Type': 'text/plain'});
response.end();
}
var name = params.name;
var workDesc = params.workDesc;
var wLoc = params.wLoc;
var DOC = params.DOC;
var severity = params.severity;
console.log("Name: " + name);
console.log("Work Description: " + workDesc)
console.log("Location: " + wLoc)
console.log("Date of Creation: " + DOC)
console.log("Severity: " + severity);
console.log("");
writeOut(200);
}
var server = http.createServer(handler);
server.listen(80);
在HTML页面上运行的脚本:
var load = function()
{
getDate();
getLocation();
}
var verifyWords = function (ev) {
var text = document.getElementById("workDesc").value;
if (text.split(" ").length > 299)
document.getElementById("workDesc").style.borderColor = "red";
//return true;
};
var getDate = function () {
var updateItem = document.getElementById("date");
var today = new Date();
var day = today.getDate();
var month = today.getMonth() + 1;
var year = today.getFullYear();
if (day < 10)
day = '0' + day;
if (month < 10)
month = '0' + month;
today = year + '-' + month + '-' + day;
updateItem.innerHTML = today;
};
var getLocation = function () {
var updateItem = document.getElementById("location");
var locationInfo = function (position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var alt = position.coords.altitude;
var info = "Latitude: " + lat + "<br />" + "Longitude: " + lon + "<br />" + " Altitude: " + alt;
var btn = document.getElementById("geoBtn");
updateItem.innerHTML = info;
updateItem.appendChild(btn);
}
var locationError = function (error) {
var errMsg = ['',
'Permission denied',
'Position unavailable',
'timeout'];
updateItem.value = ("Error receiving location info: " +
errMsg[error.code]);
updateItem.style.Color = "rgba(255,0,0,.4)";
}
var options = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 30000
};
var watchId = navigator.geolocation.getCurrentPosition(
locationInfo, locationError);
};
var submitted = function (form) {
var loc = document.getElementById("location");
var severity = document.getElementById("severity");
var desc = document.getElementById("workDesc");
var good = true;
if (document.getElementById("name").value.length < 3) {
document.getElementById("name").style.backgroundColor = "rgba(255,0,0,.3)";
good = false;
}
if (desc.value.split(" ").length > 299) {
desc.style.borderColor = "red";
good = false;
}
if (desc.value.length < 2) {
workDesc.style.backgroundColor = "rgba(255,0,0,.3)";
good = false;
}
if (!(loc.innerHTML.length > 0 && loc.innerHTML.indexOf("Error") === -1 && loc.innerHTML.indexOf("Lat") >= 0)) {
loc.style.backgroundColor = "rgba(255,0,0,.3)";
good = false;
} else if (severity.value === "default") {
severity.style.backgroundColor = "rgba(255,0,0,.3)";
good = false;
}
if (good) {
startSubmitData();
}
};
var startSubmitData = function () {
try {
if (submitData() === true)
return true;
}
catch (err)
{
saveLocal();
}
};
var clear = function()
{
var nam = document.getElementById("name");
nam.style.backgroundColor = "white";
var dat = document.getElementById("date");
dat.style.backgroundColor = "white";
var loc = document.getElementById("location");
loc.style.backgroundColor = "white";
var sev = document.getElementById("severity");
sev.style.backgroundColor = "white";
var desc = document.getElementById("workDesc");
desc.style.backgroundColor = "white";
dat.innerHTML = desc.value = "";
var btn = document.getElementById("geoBtn");
loc.innerHTML = "";
loc.appendChild(btn);
sev.selectedIndex = 0;
getDate();
}
var saveLocal = function () {
try {
var nam = document.getElementById("name");
var dat = document.getElementById("date");
var loc = document.getElementById("location");
var btn = document.getElementById("geoBtn");
loc.removeChild(btn);
var sev = document.getElementById("severity");
var desc = document.getElementById("workDesc");
alert("local");//Do localstorage
var i = 0;
while (localstorage["name" + i].length > 0)
i++;
localStorage["name" + i] = nam.value;
localStorage["date" + i] = dat.innerHTML;
localStorage["sev" + i] = sev.value;
localStorage["desc" + i] = desc.value;
localStorage["locaton" + i] = loc.innerHTML;
clear();
}
catch (err) {
alert("Localstorage is not defined. Is this running from file:///?");
}
};
HTML页面:
<!DOCTYPE html>
<html lang="en" manifest="cache.appcache">
<head>
<title>Create Work Order</title>
<meta name="viewport" content="width=1060">
<script src="project.js" type="text/javascript"></script>
<script src="network.js" type="text/javascript"></script>
<script src="jquery-2.0.3.js"></script>
<script>
function eval(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[a-zA-Z]/;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}</script>
<link rel="stylesheet" href="project.css" type="text/css" />
</head>
<header id="title">
<h2 class="title2">Create Work Order</h2>
</header>
<body onload="load()">
<div>
<section id="workForm">
<label>First name:</label>
<input type="text" id="name" style="width:20%" onkeypress="eval(event)" />
<Label>Last name:</label>
<input type="text" id="lastName" style="width: 20%" onkeypress="eval(event)"/>
<br />
<br />
<label>Work Description:</label>
<br />
<textarea id="workDesc" placeholder="Enter up to 300 words here." onkeyup="verifyWords(event)" maxlength="3000"></textarea>
<br />
<label>Work Location:</label>
<p id="location">
<input type="button" value="Refresh Location" id="geoBtn" onclick="getLocation()" style="float:right; margin-right:50%; height:3em;" />
</p>
<br />
<label>Date of creation:</label>
<p id="date"></p>
<br />
<label>Severity:</label>
<br />
<select id="severity" name="severity" style="margin-top:5px;">
<option value="default">Select One</option>
<option value="MINOR">Minor</option>
<option value="MAJOR">Major</option>
<option value="URGENT">Urgent</option>
</select>
<br />
<input id="submit" type="button" value="Submit" onclick="submitted(event)"/>
</section>
</div>
</body>
</html>
最后,我的network.js代码(提交时调用):
var submitData = function () {
var loc = document.getElementById("location").innerHTML;
var ind = loc.indexOf("<input");
var loc = loc.substring(0, ind);
//var dataString = "name=" + document.getElementById("name").value + "&workDesc=" + workDesc.value + "&DOC=" + date.innerHTML + "&severity=" + severity.value + "&wLoc=" + loc;
var dataString = "name=Joe&workDesc=Test&DOC=8-5-2013&severity=MAJOR&wLoc=Latitude: 23234 Longitude:-239823 Altitude:Unavailable";
alert(dataString);
$.ajax({
type: "GET",
url: "http://localhost/",
data: dataString,
success: function () {
clear();
},
error: function()
{
saveLocal();
alert("Could not connect to server.");
}
});
submitLocal();
return true;
}
var submitLocal = function()
{
};
我意识到这是需要阅读的大量代码。如果我能以任何方式更容易阅读或更容易理解,请通过留言给我。
答案 0 :(得分:0)
您应该序列化对象,而不是手动构建查询字符串:
var data = {
name: "Joe",
workDesc: "Test",
DOC: "8-5-2013",
severity: "MAJOR",
wLoc: "Latitude: 23234 Longitude:-239823 Altitude:Unavailable"
};
$.ajax({
type: "GET",
url: "http://localhost/",
data: data,
success: function () {
clear();
},
error: function()
{
saveLocal();
alert("Could not connect to server.");
}
});