如何将JS对象传递给PHP函数 $('.select_category')。更改(函数(){ 如果($(this).is(':checked')){ var ID=$(this.val(); $.ajax({ url:“”, 类型:'POST', 数据:{category_id:1}, 数据类型:“json”, 成功:功能(数据){ $(“#attribute_form”).html(“
这里需要做的是,使用Ajax将数据发送到一个单独的php页面,并向其传递一些信息,然后,基于这些信息,php页面应该将数据返回到Ajax回调函数,该函数将返回的数据添加到原始页面 下面是一个简单的例子: 在如何将JS对象传递给PHP函数 $('.select_category')。更改(函数(){ 如果($(this).is(':checked')){ var ID=$(this.val(); $.ajax({ url:“”, 类型:'POST', 数据:{category_id:1}, 数据类型:“json”, 成功:功能(数据){ $(“#attribute_form”).html(“,php,jquery,object,Php,Jquery,Object,这里需要做的是,使用Ajax将数据发送到一个单独的php页面,并向其传递一些信息,然后,基于这些信息,php页面应该将数据返回到Ajax回调函数,该函数将返回的数据添加到原始页面 下面是一个简单的例子: 在index.html中执行以下操作: $('.select_category').change(function(){ if($(this).is(':checked')){ var ID = $(this).val(); $.a
index.html
中执行以下操作:
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'<?php echo site_url($this->config->item('admin_folder').'/catalog/get_all_option');?>',
type:'POST',
data:{category_id:1},
dataType: 'json',
success:function(data){
$('#attribute_form').html('<?php add_attribute_form("'+data+'");?>');
}
});
}
});
嗯,你不能那样调用PHP函数。在浏览器中呈现页面后,你就不能这样做。你必须使用JavaScript/jQuery执行你的函数所做的操作,但当我传递自定义数据(如add_attribute_form('yasir'))时,它可以正常工作它显示在#attribute_form div上,但实际上我将对象传递给了函数。您需要知道的是,PHP标记(
)中的指令是在页面传输到用户代理之前执行的,因此您永远不会在交付的页面中看到PHP标记!以及添加属性_form()
函数也将在手之前执行,无论您将yasir
或'+data+'
作为PHP函数的参数!!
<script>
$(document).ready(function(){
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'somepage.php',
type:'POST',
data:{category_id:1},
dataType: 'json', // this setting means you expect the server to return json formatted data
// this is important because if the data you get back is not valid json,
// the success callback below will not be called,
// the error callback will be called instead
success:function(response){
$('#attribute_form').html(response.html);
// if not using json, this would just be $('#attribute_form').html(response);
},
error:function(xhr, status, error){
// handel error
}
});
}
});
});
</script>
<input type="checkbox" class="select_category"> Check this box
<div id="attribute_form"></div>
<?php
$category_id = isset($_POST['category_id']) ? $_POST['category_id'] : null;
if($category_id == '1'){
echo json_encode(array('html'=>'<h1>This text came from the php page</h1>'));
exit;
// if you are not using dataType:json in your ajax, you can just do:
// echo '<h1>This text came from the php page</h1>';
// exit;
}
?>