weixin_33694620 2013-08-06 03:30 采纳率: 0%
浏览 42

Ajax写入服务器问题

I have a very unique (and very in-depth) problem. If either of those two characteristics don't appeal to you, please don't feel the need to read on.

I have a program that I have written from scratch. It is creating an HTML page, allowing a user to insert data into that page, and then submitting that data.
Upon submit, the data writes to a node.js server I am running locally on my machine. Its only job is to take the data passed to it, and print it to the console that started it (a cmd prompt in this case)
It writes via a querystring in the URL, i.e. http://localhost/?<parametersGoHere>
The client files (HTML page, javascript program) are also being hosted using a node.js module called http-server. Link to the module: https://github.com/nodeapps/http-server
(Example: going into the directory where all of my files are stored, and running the command "http-server" hosts all of my files on localhost:8080)

This is my issue: when writing to the node.js server, the ajax call fails every single time.
I can physically write out a URL that includes parameters with values, and the server will spit out the correct data every time.

I've looked at this in google chrome's developer tools, and can see it's having issues contacting the address I list. But the problem is, it's the exact same url as the one I can manually type in and get results with.
That being said, the error (in my opinion) is somewhere in the network.js file. Can anyone help me find this error?



Server: (ran with node server.js in its directory on a command prompt)

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);


Scripts running on the HTML page:

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 Page:

<!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>


Lastly, my network.js code (called when submit occurs):

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()
{
}; 



I realize this is a lot of code to read through. Please let me know if I can make this easier to read in any way, or easier to understand, by leaving me a comment.

  • 写回答

1条回答 默认 最新

  • weixin_33709590 2013-08-06 03:37
    关注

    You should be serializing an object instead of constructing the query string manually:

    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.");
        }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮