jQuery 직렬화 양식을 PHP 직렬화 해제하려면 어떻게해야합니까?
를 사용하여 $('#form').serialize()
이것을 PHP 페이지로 보낼 수있었습니다. 이제 PHP에서 어떻게 직렬화를 해제합니까? jQuery에서 직렬화되었습니다.
jquery serialize
메소드 에서 PHP의 직렬화를 해제 할 필요는 없습니다 . 데이터를 직렬화하는 경우 GET 메소드 ajax 요청을 사용하는 경우 데이터를 PHP에 쿼리 매개 변수로 보내거나 POST ajax 요청을 사용하는 경우 var를 게시해야합니다. 따라서 PHP에서는 요청 유형에 따라 $_POST["varname"]
또는 $_GET["varname"]
요청 유형에 따라 값에 액세스합니다 .
이 serialize
메소드는 양식 요소를 가져 와서 문자열 양식으로 넣습니다."varname=val&var2=val2"
서버가 다음과 같은 문자열을 수신하고 있다면 (jQuery 사용하는 경우 serialize()
)
"param1=someVal¶m2=someOtherVal"
... 이것은 아마도 당신이 필요로하는 것입니다 :
$params = array();
parse_str($_GET, $params);
$params
그런 다음 예상대로 모델링 된 배열이어야합니다. 이것은 HTML 배열에서도 작동합니다.
자세한 내용은 다음을 참조하십시오. http://www.php.net/manual/en/function.parse-str.php
도움이 되길 바랍니다. 행운을 빕니다!
// jQuery Post
var arraydata = $('.selector').serialize();
// jquery.post 직렬화 된 var-TO-PHP 배열 형식
parse_str($_POST[arraydata], $searcharray);
print_r($searcharray); // Only for print array
// 당신은 그것의 어떤 것을 얻는다
Array (
[A] => 1
[B] => 2
[C] => 3
[D] => 4
[E] => 5
[F] => 6
[G] => 7
[H] => 8
)
parse_str($_POST['whatever'], $searcharray);
에서 HTML의 페이지 :
<script>
function insert_tag()
{
$.ajax({
url: "aaa.php",
type: "POST",
data: {
ssd: "yes",
data: $("#form_insert").serialize()
},
dataType: "JSON",
success: function (jsonStr) {
$("#result1").html(jsonStr['back_message']);
}
});
}
</script>
<form id="form_insert">
<input type="text" name="f1" value="a"/>
<input type="text" name="f2" value="b"/>
<input type="text" name="f3" value="c"/>
<input type="text" name="f4" value="d"/>
<div onclick="insert_tag();"><b>OK</b></div>
<div id="result1">...</div>
</form>
에 PHP의 페이지 :
<?php
if(isset($_POST['data']))
{
parse_str($_POST['data'], $searcharray);
$data = array(
"back_message" => $searcharray['f1']
);
echo json_encode($data);
}
?>
이 PHP 코드에서 f1
필드를 반환하십시오 .
연관 배열을 사용하지 않는 이유는 무엇입니까?
function unserializeForm($str) {
$returndata = array();
$strArray = explode("&", $str);
$i = 0;
foreach ($strArray as $item) {
$array = explode("=", $item);
$returndata[$array[0]] = $array[1];
}
return $returndata;
}
문안 인사
수정 된 Murtaza Hussain 답변 :
function unserializeForm($str) {
$strArray = explode("&", $str);
foreach($strArray as $item) {
$array = explode("=", $item);
$returndata[] = $array;
}
return $returndata;
}
간단히 이렇게
$get = explode('&', $_POST['seri'] ); // explode with and
foreach ( $get as $key => $value) {
$need[ substr( $value, 0 , strpos( $value, '=' ) ) ] = substr( $value, strpos( $value, '=' ) + 1 ) ;
}
// access your query param name=ddd&email=aaaaa&username=wwwww&password=wwww&password=eeee
var_dump( $need['name'] );
사용중인 Jquery 버전을 모르지만 jquery 1.3에서 작동합니다.
$.ajax({
type: 'POST',
url: your url,
data: $('#'+form_id).serialize(),
success: function(data) {
$('#debug').html(data);
}
});
그런 다음 일반적으로 PHP에서와 같이 POST 배열 키에 액세스 할 수 있습니다. 로 시도하십시오 print_r()
.
I think you're wrapping serialized form value in an object's property, which is useless as far as i know.
Hope this helps!
This is in reply to user1256561. Thanks for your idea.. however i have not taken care of the url decode stuff mentioned in step3.
so here is the php code that will decode the serialized form data, if anyone else needs it. By the way, use this code at your own discretion.
function xyz($strfromAjaxPOST)
{
$array = "";
$returndata = "";
$strArray = explode("&", $strfromPOST);
$i = 0;
foreach ($strArray as $str)
{
$array = explode("=", $str);
$returndata[$i] = $array[0];
$i = $i + 1;
$returndata[$i] = $array[1];
$i = $i + 1;
}
print_r($returndata);
}
The url post data input will be like: attribute1=value1&attribute2=value2&attribute3=value3 and so on
Output of above code will still be in an array and you can modify it to get it assigned to any variable you want and it depends on how you want to use this data further.
Array
(
[0] => attribute1
[1] => value1
[2] => attribute2
[3] => value2
[4] => attribute3
[5] => value3
)
You just need value attribute name in form. Example :
Form
<form id="login_form">
<input type="text" name="username" id="a"/>
<input type="password" name="password" id="b"/>
<button type="button" onclick="login()">Submit</button>
</form>
Javascript
$(document).ready(function(){});
function login(){
var obj = $('#login_form').serialize();
$.post('index.php', obj, function(res){
alert(res);
})
}
PHP - index.php
<?php
if(!empty($POST['username']) && !empty($POST['password'])){
$user = $POST['username'];
$pass = $POST['password'];
$res = "Username : ".$user." || Password : ".$pass;
return $res;
}
?>
I think you need to separate the form names from its values, one method to do this is to explode (&)
so that you will get attribute=value,attribute2=value
.
My point here is that you will convert the serialized jQuery string into arrays in PHP.
Here is the steps that you should follow to be more specific.
- Passed on the serialized
jQuery
to aPHP
page(e.gajax.php
) where you use$.ajax
to submit using post or get. - From your php page, explode the
(&)
thus separating each attributes. Now you will get attribute1=value, attribute2=value, now you will get a php array variable. e.g$data = array("attribute1=value","attribute2=value")
- Do a
foreach
on$data
andexplode
the(=)
so that you can separate the attribute from the value, and be sure tourldecode
the value so that it will convert serialized values to the value that you need, and insert the attribute and its value to a new array variable, which stores the attribute and the value of the serialized string.
Let me know if you need more clarifications.
Use:
$( '#form' ).serializeArray();
Php get array, dont need unserialize ;)
참고URL : https://stackoverflow.com/questions/1792603/how-do-i-php-unserialize-a-jquery-serialized-form
'Programing' 카테고리의 다른 글
컨트롤러에서 양식에 액세스 할 수 있습니까? (0) | 2020.06.12 |
---|---|
작곡가 설치 오류-실제로 활성화 된 경우 ext_curl 필요 (0) | 2020.06.12 |
사전을 사용하여 목록의 항목 수 (0) | 2020.06.12 |
PHP에서 중단과 계속의 차이점은 무엇입니까? (0) | 2020.06.12 |
angularjs : background-image : url (…)에 해당하는 ng-src (0) | 2020.06.12 |