2017-12-31 159 views
0

그래서 동일한 루트 디렉토리에있는 data.txt에서 hello world 텍스트를 반환하는 간단한 Ajax 요청을 작성하려고합니다.AJAX : request.status == 200 false를 반환합니까? (데이터가 페이지에 표시되지 않음)

문제 : 상태를 확인할 때 === 200 문에 이 표시되지 않는 경우 즉, 아무 것도 true를 반환하지 않는 경우.

TWIST :.하지만 if 문이 요청이 에 콘솔을 기록됩니다 (그러나 데이터가 페이지에 기록되지 않는 제거하면

CODE

// AJAX REQUEST EXAMPLE 
// XHR is the api that is used for AJAX REQUESTS 
// Create a XHR request object 

var request = new XMLHttpRequest(); 
// create the 'request' for this object. open() reqest method GET/POST, location of the data file (ajax requests has same domain poilcy - so you can't request data objects for domains from other than what your currently on), true/fasle (whether we want request ot be asyncronous or not fasle means its asyc i.e. brwoser waits until requests is done before it does anything else) 
request.open('GET', 'data.txt', true); 
// send request to the server for data 
request.send(); 
if (request.status=== 200) { 
    document.writeln(request.responseText); 

} 
    console.log(request); 
+0

는 분명하지 않다. –

답변

1

이것이 당신을 이해하는 데 도움이되기를 바랍니다. 나는 당신에게 몇 가지 코멘트를 남겼습니다. 나에게 모든 것을 물어 주시기 바랍니다 :

<!DOCTYPE html> 

<html> 

<head> 
    <meta charset="utf-8"> 
    <title>stackoverflow test</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
</head> 

<body> 

    <script type="text/javascript"> 
    // AJAX REQUEST EXAMPLE 
    // XHR is the api that is used for AJAX REQUESTS 
    // Create a XHR request object 

    var request = new XMLHttpRequest(); 


    request.onreadystatechange = function() //This is to wait for response (eventually from your PHP script) 
    { 
     if (request.readyState === 4 && request.status === 200) //And when status is OK use result 
     { 

     document.writeln(request.responseText); 
     console.log(request.status); //here the status request 
     console.log(request); //here the complete object request 
     } 
    } 

    // open() request method GET/POST, location of the data file (ajax requests has same domain policy - so you can't request data objects for domains from other than what your currently on), true/false (whether we want request ot be asyncronous or not false means its asyc i.e. browser waits until requests is done before it does anything else) 
    request.open('GET', 'data.txt', true); 
    // send request to the server for data 
    request.send(); 


    </script> 


</body> 

</html> 

는 이제 브라우저 콘솔에서 success request, 브라우저에서 data.txt 출력으로 200을 얻을 것이다.

stack_example

는 건배, 줄리오

+0

코드가 작동한다. 2 질문 : request.readyState === 4를 확인하고 onreadystatechange를 추가한다.() 코드가별로 다르지 않은데 왜 내 코드가 작동하지 않습니까? 아이디어 :) – Shaz

+0

질문 2 : onreadystatechange가 필요하며 PHP로 그 목적은 무엇입니까? – Shaz

+0

내가 근본적으로 잘못하고있는 것을 알아 내기 위해 반복하지 않으려 고 함) – Shaz

관련 문제