我是通过AJAX传递对象的新手,因为我不确定传递和检索,所以我在调试时遇到问题。
基本上,我正在向PHP控制器发出AJAX请求,并将数据回显到页面。我无法确定我是否成功通过了我的对象。打印到我的页面视图时,我得到null。
这是我的js:
// creating a js filters object with sub arrays for each kind
var filters = {};
// specify arrays within the object to hold the the list of elements that need filtering
// names match the input name of the checkbox group the element belongs to
filters['countries'] = ["mexico", "usa", "nigeria"];
filters['stations'] = ["station1", "station2"];
filters['subjects'] = ["math", "science"];
// when a checkbox is clicked
$("input[type=checkbox]").click(function() {
// send my object to server
$.ajax({
type: 'POST',
url: '/results/search_filter',
success: function(response) {
// inject the results
$('#search_results').html(response);
},
data: JSON.stringify({filters: filters})
}); // end ajax setup
});
我的PHP控制器:
public function search_filter() {
// create an instance of the view
$filtered_results = View::instance('v_results_search_filter');
$filtered_results->filters = $_POST['filters'];
echo $filtered_results;
}
我的PHP视图:
<?php var_dump($filters);?>
也许我需要使用jsondecode PHP函数,但我不确定我的对象是否首先被传递。
答案 0 :(得分:3)
IIRC $ .ajax jQuery方法的数据属性直接接受json数据,不需要在这里使用JSON.stringify:
data: {filters: filters}
这样,您就可以将json数据作为常规键/值对接收,适合通过$ _POST超全局数组在PHP中读取,如您所料。
答案 1 :(得分:2)
http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php
使用ajax时,页面不会重新加载,因此php变量无法使用。
您可能需要寻找帮助的教程。我在开头放了一个,因为我看不到如何在平板电脑上格式化这个
您将需要按照教程显示
对您的回复进行json_encode当您使用php函数时,您可能希望打印到服务器上的日志,并使其可读取,以便您可以通过浏览器访问它
我喜欢使用Chrome中的开发者工具来查看从服务器实际返回的内容