【问题标题】:How to pass JS object to PHP function如何将 JS 对象传递给 PHP 函数
【发布时间】:2015-11-23 23:41:09
【问题描述】:
$('.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+'");?>');


                }

            });
        }

    });

回调函数成功返回数据并将其传递给 add_attribute_form(data) php 函数但没有响应。 将js对象传递给php函数的正确方法是什么

【问题讨论】:

  • 哼,你不能这样调用PHP函数。在页面已经在浏览器中呈现之后,您就不能这样做了。您必须使用 JavaScript/jQuery 完成您的功能
  • 但是当我传递像 add_attribute_form('yasir') 这样的自定义数据并且它显示在#attribute_form div 上时它工作正常但我实际上将对象传递给函数。
  • 您需要知道的是,PHP 标记 (&lt;?php ... ?&gt;) 内的指令是在 页面传输到用户代理之前执行的,因此您将永远不会在交付的页面中看到 PHP 标记!并且add_attribute_form()函数也会提前执行,无论你传递yasir还是'+data+'作为PHP函数的参数!!

标签: php jquery object


【解决方案1】:

您需要在这里做的是,使用 Ajax 将数据发送到 单独的 php 页面并传递一些信息,然后,基于该信息,php 页面应该 返回 数据到 Ajax 回调函数,它将返回的数据添加到原始页面。

这是一个简单的例子(and a working demo here)

index.html 中这样做:

<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>

然后在somepage.php 中执行以下操作:

<?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;
}
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    相关资源
    最近更新 更多