0

我有一个非常独特(而且非常深入)的问题。如果这两个特征中的任何一个对您没有吸引力,请不要觉得有必要继续阅读。

我有一个从头开始编写的程序。它正在创建一个 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 文件中的某个位置。谁能帮我找到这个错误?



服务器:(在命令提示符的目录中使用 node 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()
{
}; 



我意识到这是很多需要阅读的代码。请让我知道我是否可以通过给我发表评论以任何方式使其更易于阅读或更易于理解。

4

1 回答 1

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.");
    }
});
于 2013-08-06T03:37:39.610 回答