我刚刚理解 js 中的数组无法包含值的键,所以我正在寻找将数组从 js 传递到 php 并返回的选项。当我搜索相关信息时,我找到了 json 选项。但我看到 js 不完全支持,除非你在我的情况下添加插件 json2.js 。我有两个不同的代码,它们运行 $.post
良好 $.ajax
但不起作用。如果你告诉我为什么$.ajax
不工作,我会很高兴你有完整的代码可以测试。json2.js 来自这里.thx
$.ajax
代码:
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "phpfile.php",
data: "{ data : dataString }",
dataType: "json",
success: function (res) {
alert('sucsses');
var obj = jQuery.parseJSON(res);
if(obj.somebool === true)
$("#result").html(obj.hello + ' ' + obj.array[1] + obj.worked + ". Message from PHP: "+obj.php_message);
},
error: alert ('there was problem with ajax');
});
*
$.post
代码:
$.post('phpfile.php', {data: dataString}, function(res){
alert('sucsses');
var obj = jQuery.parseJSON(res);
if(obj.somebool === true)
$("#result").html(obj.hello + ' ' + obj.array[1] + obj.worked + ". Message from PHP: "+obj.php_message);
});
html代码:
<html>
<head>
<title>Json Test</title>
<SCRIPT src="jquery-1.7.2.min.js"></SCRIPT>
<SCRIPT src="json2.js"></SCRIPT>
<script>
$(document).ready(function(){
var data = new Object();
data.hello = "Hello";
data.world = 'World';
data.worked = " it worked ";
data.somebool = true;
data.array = new Array("he\"ll\"o", '"World"');
alert (data.hello);
var dataString = JSON.stringify(data);
alert(dataString);
$.post('phpfile.php', {data: dataString}, function(res){
alert('sucsses');
var obj = jQuery.parseJSON(res);
if(obj.somebool === true)
$("#result").html(obj.hello + ' ' + obj.array[1] + obj.worked + ". Message from PHP: "+obj.php_message);
});
});
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>
php代码:
<?php
$res = json_decode($_REQUEST['data'], true);
$res["php_message"] = "I am PHP";
echo json_encode($res);
?>