2013-08-06 2 views
0

매우 독특한 (매우 심층적 인) 문제점이 있습니다. 이 두 가지 특성 중 하나라도 호소력이 없다면 계속해서 읽어야 할 필요성을 느끼지 마십시오.Ajax 서버에 쓰기 문제

나는 처음부터 쓴 프로그램이있다. HTML 페이지를 작성하여 사용자가 해당 페이지에 데이터를 삽입 한 다음 해당 데이터를 제출할 수 있도록합니다.
제출하면 node.js 서버에 데이터가 기록됩니다. 내 컴퓨터에서 로컬로 실행 중입니다. 유일한 작업은 전달 된 데이터를 가져 와서 시작한 콘솔 (이 경우 cmd 프롬프트)에 인쇄하는 것입니다.
URL의 쿼리 문자열을 통해 작성합니다. 즉 http://localhost/?<parametersGoHere>
클라이언트 파일 (HTML 페이지 , 자바 스크립트 프로그램)도 http-server라는 node.js 모듈을 사용하여 호스팅됩니다. 모듈 링크 : https://github.com/nodeapps/http-server
(예 : 내 모든 파일이 저장된 디렉토리로 진행하고 명령 "HTTP 서버가"localhost:8080 내 모든 파일을 호스트 실행)이 내 문제가

입니다 : node.js 서버에 쓸 때마다 ajax 호출이 매번 실패합니다.
필자는 값이있는 매개 변수를 포함하는 URL을 실제로 작성할 수 있으며, 서버는 매번 정확한 데이터를 출력합니다.

Google 크롬 개발자 도구에서이 문제를 조사한 결과, 내가 언급 한 주소로 문의하는 데 문제가 있음을 알 수 있습니다. 그러나 문제는 입니다. 수동으로 입력하여 결과를 얻을 수있는 URL과 완전히 동일합니다.
오류 (내 의견으로는)는 network.js 파일의 어딘가에 있다고 말합니다. 누구든지이 오류를 찾도록 도와 줄 수 있습니까?



서버 :

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 : HTML 페이지에서 실행

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


스크립트 (명령 프롬프트에 그 디렉토리에있는 노드 server.js으로 실행) 페이지 :

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

봐. 실패한 요청을 클릭하십시오. 성공한 페이지와 어떻게 다른가요? (하단의 작은 회색 원을 클릭하여 페이지 전체의 요청 정보 유지) – Blender

+0

아직이 데이터가 없기 때문에이 데이터와의 성공적인 요청과 다른 점을 말할 수 없습니다. 내 Ajax/send 호출이 실패하기 때문에 (일반적으로) 성공적인 요청과 다릅니다. Chrome의 개발자 도구에 그렇게 뛰어나지 않습니다. 더 자세하게 설명해 주시겠습니까? – Baelix

+0

새 탭을 열고 개발자 도구를 열고 네트워크로 이동하십시오. 여기에서 탐색 할 때 요청을 보존하려면 하단 막대의 작은 검은 색 원을 클릭하십시오. 개발자 도구가 열려있는 상태에서 주소 표시 줄에 URL을 입력하고 Enter 키를 누릅니다. 표에서 결과 행을 클릭하십시오. 실패한 AJAX 요청과 다른 점을 확인하십시오. 동일한 AJAX 요청을 동일한 탭에서 보내면 실패합니다. – Blender

답변

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."); 
    } 
}); 
+0

이것은 저에게 문제를 해결하지 못했습니다. – Baelix

+0

대신 내 서버에서 JSON 객체를 구문 분석해야 할 필요가 있을까요? – Baelix

+0

@baelix 주위에 직렬화 된 자바 스크립트 객체를 전송할 때 자바 스크립트 객체로 다시 사용할 수 있도록 수신 측에서 직렬화 해제해야합니다. 이것은 실제로 모든 직렬화 된 데이터에 적용됩니다. 참조 : http://en.wikipedia.org/wiki/Serialization – pygeek