Javascript에서 PHP로 JSON 데이터를 보내시겠습니까?
브라우저의 Javascript에서 서버로 JSON 데이터를 전송하여 PHP로 해석하려면 어떻게 해야 합니까?
저는 여기서 많은 정보를 얻었기 때문에 제가 발견한 해결책을 게시하고 싶었습니다.
문제:브라우저의 Javascript에서 서버로 JSON 데이터를 가져와 PHP에 의해 정상적으로 해석됩니다.
환경: Windows의 브라우저(Firefox)에서 Javascript를 사용할 수 있습니다.원격 서버로서의 LAMP 서버: Ubuntu의 PHP 5.3.2.
1) : ★★★★★★★★★★★★★★★★★★★★★★1)
입니다. 1) JSON은 텍스트입니다.텍스트는 특정 형식이지만 텍스트 문자열에 불과합니다.
Javascript, 2) Javascript ★var str_json = JSON.stringify(myObject)JSON 문자열이 표시됩니다.
에서 AJAX 합니다. 3) Javascript ajax AJAX XMLHttpRequest 체 、 3 3 3 3 3 3 3 3 。
request= new XMLHttpRequest()
request.open("POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(str_json)
[... code to display response ...]
4) 서버에서 JSON 문자열을 읽기 위한 PHP 코드:
$str_json = file_get_contents('php://input');
Raw POST ★★★★★★★★★★★★★★★★★★★★★★★★」 $str_jsonJSON을 사용하다
2) : ★★★★★★★★★★★★★2)
) 1) 을 경우"application/x-www-form-urlencoded"header, header의 인 "POST"를 ."x=y&a=b[etc]"를 통해 PHP는를 취득했을 때 PHP를 PHP는 PHP는 PHP를 할 수 .$_POST을 수행합니다자바스크립트
var str_json = "json_string=" + (JSON.stringify(myObject))
AJAX/XMLHttpRequest는 Str_json은 PHP $_POST를 사용합니다.
의 $_POST['json_string']JSON 문문문다다다다다다다다sonsonsonsonson.$_POST 어레이 요소에서 json_decode()를 json 문자열과 함께 사용하면 데이터가 올바르게 디코딩되어 어레이/개체에 저장됩니다.
'이것'은 다음과 같습니다.
application / x - www - form - urlencoded sonsonJSON 、 PHP _ $ _ POST ______ 。$_POST $ $ $ $ $ $ $ $ $ $ 。yval=xval&[filen_and_filen]을 클릭합니다.JSON 문자열만 찾을 뿐 이러한 데이터는 발견되지 않았고 그냥 버렸습니다.요청 헤더를 조사했더니 POST 데이터가 올바르게 전송되고 있었습니다.
마찬가지로 application/json 헤더를 사용하면 $_POST 어레이를 통해 전송된 데이터에 다시 액세스할 수 없습니다.응용 프로그램/json 콘텐츠 타입 헤더를 사용하려면 $_POST가 아닌 php://input을 통해 PHP의 원시 POST 데이터에 액세스해야 합니다.
고고: :
1) PHP에서 POST 데이터에 액세스하는 방법: PHP에서 POST 데이터에 액세스하는 방법
2) 어플리케이션/json 타입의 상세 및 JSON 문자열로 변환하여 서버로 전송할 수 있는 샘플오브젝트:http://www.ietf.org/rfc/rfc4627.txt
jQuery를 사용한 Javascript 파일(깨끗하지만 라이브러리 오버헤드):
$.ajax({
type: 'POST',
url: 'process.php',
data: {json: JSON.stringify(json_data)},
dataType: 'json'
});
PHP 파일(process.php):
directions = json_decode($_POST['json']);
var_dump(directions);
javascript에서 콜백 함수를 사용하는 경우:
$.ajax({
type: 'POST',
url: 'process.php',
data: {json: JSON.stringify(json_data)},
dataType: 'json'
})
.done( function( data ) {
console.log('done');
console.log(data);
})
.fail( function( data ) {
console.log('fail');
console.log(data);
});
Javascript 코드에서 '완료/성공' 결과를 얻으려면 PHP 파일에서 JSON 객체(javascript 형식)를 반환해야 합니다.최소 반품/인쇄:
print('{}');
Ajax 요청이 200 OK를 반환하지만 성공 대신 오류 이벤트가 발생함을 참조하십시오.
조금 더 심각한 경우에는 적절한 응답 코드를 사용하여 적절한 헤더를 명시적으로 반환해야 합니다.
HTML 입력 필드용 JavaScript의 간단한 예(서버 JSON으로 전송, PHP로 JSON 구문 분석 및 클라이언트로 반송)는 AJAX를 사용합니다.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<body>
<div align="center">
<label for="LName">Last Name</label>
<input type="text" class="form-control" name="LName" id="LName" maxlength="15"
placeholder="Last name"/>
</div>
<br/>
<div align="center">
<label for="Age">Age</label>
<input type="text" class="form-control" name="Age" id="Age" maxlength="3"
placeholder="Age"/>
</div>
<br/>
<div align="center">
<button type="submit" name="submit_show" id="submit_show" value="show" onclick="actionSend()">Show
</button>
</div>
<div id="result">
</div>
<script>
var xmlhttp;
function actionSend() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var values = $("input").map(function () {
return $(this).val();
}).get();
var myJsonString = JSON.stringify(values);
xmlhttp.onreadystatechange = respond;
xmlhttp.open("POST", "ajax-test.php", true);
xmlhttp.send(myJsonString);
}
function respond() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('result').innerHTML = xmlhttp.responseText;
}
}
</script>
</body>
</html>
PHP 파일 ajax-test.php :
<?php
$str_json = file_get_contents('php://input'); //($_POST doesn't work here)
$response = json_decode($str_json, true); // decoding received JSON to array
$lName = $response[0];
$age = $response[1];
echo '
<div align="center">
<h5> Received data: </h5>
<table border="1" style="border-collapse: collapse;">
<tr> <th> First Name</th> <th> Age</th> </tr>
<tr>
<td> <center> '.$lName.'<center></td>
<td> <center> '.$age.'</center></td>
</tr>
</table></div>
';
?>
PHP에는 json_decode()라는 함수가 내장되어 있습니다.JSON 문자열을 이 함수에 전달하기만 하면 PHP와 동등한 문자열, 배열 또는 개체로 변환됩니다.
Javascript에서 문자열로 전달하려면 , 다음의 방법으로 JSON으로 변환할 수 있습니다.
JSON.stringify(object);
또는 프로토타입과 같은 라이브러리
다음은 재현하기 쉬운 코드를 가진 주요 솔루션의 요약입니다.
메서드 1(어플리케이션/json 또는 텍스트/플레인+JSON.stringify)
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/json") // or "text/plain"
xhr.send(JSON.stringify(data));
PHP측에서는, 다음의 방법으로 데이터를 취득할 수 있습니다.
print_r(json_decode(file_get_contents('php://input'), true));
메서드 2(x-ww-form-urlencoded + JSON.stringify)
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("json=" + encodeURIComponent(JSON.stringify(data)));
★★★★★★encodeURIComponent(...)에 JSON이 포함되어 있는 합니다.&★★★★★★ 。
PHP측에서는, 다음의 방법으로 데이터를 취득할 수 있습니다.
print_r(json_decode($_POST['json'], true));
메서드 3(x-ww-form-urlencoded + URLearchParams)
var data = {foo: 'blah "!"', bar: 123};
var xhr = new XMLHttpRequest();
xhr.open("POST", "test.php");
xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { console.log(xhr.responseText); } }
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(new URLSearchParams(data).toString());
PHP측에서는, 다음의 방법으로 데이터를 취득할 수 있습니다.
print_r($_POST);
메모: https://caniuse.com/ #search=SEARCH Params
클라이언트측(HTML, Javascript, Vbscript 등)에서 서버측(PHP, ASP, JSP 등)으로 데이터를 전송하는 방법에는 3가지가 있습니다.
1. HTML form Posting Request (GET or POST).
2. AJAX (This also comes under GET and POST)
3. Cookie
HTML 폼 투고 요구(GET 또는 POST)
이것은 가장 일반적으로 사용되는 방법으로, 이 방법을 통해 더 많은 데이터를 전송할 수 있습니다.
에이잭스
이것은 비동기 방식이며 안전한 방식으로 작동해야 합니다. 여기서 더 많은 데이터를 전송할 수도 있습니다.
쿠키
이것은, 기밀성이 낮은 소량의 데이터를 사용하는 좋은 방법입니다.이것은 데이터를 처리하는 가장 좋은 방법입니다.
당신의 경우 HTML 폼 post 또는 AJAX를 선호할 수 있습니다.단, 서버로 전송하기 전에 직접 json을 검증하거나 http://jsonlint.com/과 같은 링크를 사용합니다.
JSON.stringify(object)를 사용하여 Json 객체가 문자열로 변환하는 경우 JSON 문자열이 있는 경우 그대로 전송합니다.
JSON.stringify(yourObj) 또는 Object.toJ 사용SON ( yourObj )마지막은 prototype.protype을 사용하는 경우입니다.그 후, 원하는 것을 사용해 송신합니다.ajax 또는 송신하면, 제안대로 json_protember(http://www.php.net/manual/en/function.json-decode.php )를 사용해 php로 해석할 수 있습니다.그 후 어레이로 사용할 수 있습니다.
<html>
<script type="text/javascript">
var myJSONObject = {"bindings": 11};
alert(myJSONObject);
var stringJson =JSON.stringify(myJSONObject);
alert(stringJson);
</script>
</html>
개체를 urlencoded 문자열로 쉽게 변환할 수 있습니다.
function objToUrlEncode(obj, keys) {
let str = "";
keys = keys || [];
for (let key in obj) {
keys.push(key);
if (typeof (obj[key]) === 'object') {
str += objToUrlEncode(obj[key], keys);
} else {
for (let i in keys) {
if (i == 0) str += keys[0];
else str += `[${keys[i]}]`
}
str += `=${obj[key]}&`;
keys.pop();
}
}
return str;
}
console.log(objToUrlEncode({ key: 'value', obj: { obj_key: 'obj_value' } }));
// key=value&obj[obj_key]=obj_value&
쉬운 방법을 찾았지만 완벽하지 않다는 것을 안다.
1. json의 수신처
만약 JSON이
var data = [
{key:1,n: "Eve"}
,{key:2,n:"Mom"}
];
---main.disc -----main.disc --
<form action="second.php" method="get" >
<input name="data" type="text" id="data" style="display:none" >
<input id="submit" type="submit" style="display:none" >
</form>
<script>
var data = [
{key:1,n: "Eve"}
,{key:2,n:"Mom"} ];
function setInput(data){
var input = document.getElementById('data');
input.value = JSON.stringify(data);
var submit =document.getElementById('submit');
//to submit and goto second page
submit.click();
}
//call function
setInput(data);
</script>
-------------------------------------
<script>
printJson();
function printJson(){
var data = getUrlVars()["data"];
//decode uri to normal character
data = decodeURI(data);
//for special character , / ? : @ & = + $ #
data = decodeURIComponent(data);
//remove " ' " at first and last in string before parse string to JSON
data = data.slice(1,-1);
data = JSON.parse(data);
alert(JSON.stringify(data));
}
//read get variable form url
//credit http://papermashup.com/read-url-get-variables-withjavascript/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
</script>
언급URL : https://stackoverflow.com/questions/8599595/send-json-data-from-javascript-to-php
'source' 카테고리의 다른 글
| 컨스트럭터 vs componentWillMount. componentWillMount는 컨스트럭터로는 할 수 없는 일을 componentWillMount는 어떻게 할 수 있습니까? (0) | 2023.03.08 |
|---|---|
| mongodb 그룹 값, 여러 필드별) (0) | 2023.03.08 |
| 도커를 통한 MongoDB 인증 활성화 방법 (0) | 2023.03.08 |
| 기본 Next.js 개발 서버를 사용하는 백엔드의 프록시 (0) | 2023.03.08 |
| 필요한 경우에만 모듈을 동적으로 주입합니다. (0) | 2023.03.08 |