여기이 작동하는 방법의 대략적인 그림이다 :
User's Workstation | Your Server(s)
|
+-------------+ | +-------------+ +-------------+
| Browser | | | PHP | | |
+-------------+ | +-------------+ | DB |
| JavaScript |<---------->| PHP Code |<--->| |
| code | ajax | | talks to DB | | |
+-------------+ | +-------------+ +-------------+
그래서 자바 스크립트 코드는 PHP 코드로 얘기 아약스를 사용합니다. PHP 코드가 DB와 대화한다. 인프라 스트럭처를 설정하더라도 브라우저의 JavaScript는 DB와 직접 대화하는 데 사용해서는 안됩니다. 물론 최종 사용자의 브라우저에서 실행되므로 제한된 권한을 가져야합니다. DB를 외부 세계로부터 보호해야합니다.
PHP 코드는 게이트 키퍼와 데이터 변환기 모두입니다. DB에서 데이터를 가져와 클라이언트 (일반적으로 HTML, 텍스트, JSON 또는 XML)에서 유용하게 사용할 수있는 형식으로 변환 한 다음이를 브라우저의 JavaScript 코드로 전달한 다음 해당 HTML을 사용합니다. 텍스트, JSON 또는 XML을 사용하여 사용자에게 또는 유사한 것을 보여줄 수 있습니다. (약간) 더 자세히 사람들을 보면
: 아약스 요청을 보내 자바 스크립트를 사용하여
자바 스크립트 Ajax 요청
당신이 해결할 수있는 괜찮은 라이브러리를 사용하는 경우 특히 매우 쉽습니다 일부 브라우저 불일치. 기본적으로는 다음과 같습니다
// Create the request object
var xhr = new XMLHttpRequest();
// Set up a callback for when things happen
xhr.onreadystatechange = handleReadyStateChange;
// Open the request
xhr.open("GET", "your_php_file.php");
// ^ ^----------------------- a normal URL like any other
// |------------------------------ the kind of request (GET, POST, ...)
// Send it (if this were a POST, you'd include data as an
// argument to `sent`, typically as a URI-encoded string
xhr.send();
// IMPORTANT: As of this point in the code, the request has been
// *sent*, but it has not yet *completed*. By default, ajax is
// *asynchronous*.
// Our callback for ready state changes
function handleReadyStateChange() {
// Is the request complete?
if (xhr.readyState === 4) { // 4 = complete
// Yes, did it succeed? (`status` is a standard HTTP status code
// except that *some* browsers sometimes use 0 if the response came
// from cache)
if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
// If the Content-Type header of the HTTP response was for XML,
// the XML document is on `xhr.responseXML`.
// Otherwise, the HTML, text, or JSON is on `xhr.responseText`
// ===> This is where we can use the resulting information <===
}
}
}
PHP 코드 아약스 요청이 PHP 코드를 다른 페이지 요청과 같은
:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleReadyStateChange;
xhr.open("GET", "your_php_file.php");
xhr.send();
function handleReadyStateChange() {
if (xhr.readyState === 4 && (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300))) {
// ===> This is where we can use the resulting information <===
}
}
이 더 자세히 그 살펴 보자 . (필요한 경우 따로 구분할 수는 있지만 필요한 경우는 드뭅니다.) 따라서 PHP 코드는 작성한 다른 PHP 코드와 같습니다. 그것은 아마 다른 출력을 가지고있을 것이다. PHP "페이지"를 사용하여 브라우저의 완전한 HTML 페이지를 렌더링합니다. 하지만 Ajax 요청에 응답 할 때 전체 페이지를 다시 보내지 않으면 페이지에서 사용할 코드가 다시 전송됩니다. 이
<?php
// In our case, we'll return plain text from our example, so
// mark the response accordingly
header("Content-Type", "text/plain");
// We might use $_GET or $_POST variables here, to get
// information from the request
// Once we've authenticated that the request comes from
// an authorised user, we might connect to the database
// and retrieve some information here
// Output our response
echo("Hi there");
?>
우리가 일반 텍스트를 반환하고이 단지 당신이 쓰는 다른 PHP처럼 그대로
여기 다시 PHP의 모양에 대한 하나의 예이지만, 그것은 아무것도 될 수 있습니다 . 다시 말하지만, 당신은 많은 것을 돌려 줄 수 있습니다. JSON은 데이터를 페이지로 반환 할 때 널리 사용됩니다. PHP 쪽에서는 메모리 구조 (배열 등)에 데이터를 구축 한 다음 echo
과 json_encode
을 사용하여 문자열로 변환합니다. 자바 스크립트 측면에서 최신 브라우저에서는 JSON을 JSON.parse
으로 구문 분석합니다.(이전 버전의 브라우저를 들어, 당신은 당신을 위해 하나를 제공 jQuery를 같이 좋은 라이브러리를 사용하는 또 다른 이유는 페이지,에 JSON 파서를 추가해야합니다.)
다음은 전체 예제 HTML 및 JavaScript 측 : Live Copy | 이 경우 Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Ajax Example</title>
<style>
#theSpan {
border: 1px solid grey;
padding: 2px;
}
</style>
</head>
<body>
<input type="button" id="theButton" value="Click Me">
<p>Here is the span we'll fill in: <span id="theSpan"></span></p>
<script>
(function() {
// Hook up our button click handler
document.getElementById("theButton").onclick = function() {
// Do our ajax request
// Create the request object
var xhr = new XMLHttpRequest();
// Set up a callback for when things happen
xhr.onreadystatechange = handleReadyStateChange;
// Open the request
xhr.open("GET", "/uvanep/1");
// ^ ^----------------------- a normal URL like any other
// |------------------------------ the kind of request (GET, POST, ...)
// Send it (if this were a POST, you'd include data as an
// argument to `sent`, typically as a URI-encoded string
xhr.send();
// IMPORTANT: As of this point in the code, the request has been
// *sent*, but it has not yet *completed*. By default, ajax is
// *asynchronous*.
// Our callback for ready state changes
function handleReadyStateChange() {
// Is the request complete?
if (xhr.readyState === 4) { // 4 = complete
// Yes, did it succeed? (`status` is a standard HTTP status code
// except that *some* browsers sometimes use 0 if the response came
// from cache)
if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
// If the Content-Type header of the HTTP response was for XML,
// the XML document is on `xhr.responseXML`.
// Otherwise, the HTML, text, or JSON is on `xhr.responseText`
// ===> This is where we can use the resulting information <===
// In this case, let's put it in our span:
document.getElementById("theSpan").appendChild(
document.createTextNode(xhr.responseText)
);
}
}
}
};
})();
</script>
</body>
</html>
우리가 전화하는거야 페이지는 텍스트 "Hi there"
를 반환합니다.
제목이 "결합"되어 있어야합니다 .. – dapidmini
Ajax를 사용한다는 것은 JS 또는 jQuery를 사용한다는 의미입니다. "누군가이 상황에서해야 할 일을 말해 줄 수 있니?" 분명하지 않다. – alfasin
그리고 jQuery를 사용하면 암시 적으로 JS 사용을 의미합니다. – GolezTrol