繁体   English   中英

如何将选定的值传递给 php controller

[英]How to pass selected value to php controller

我正在尝试将 ajax 的选定值传递给 php controller 但它不起作用。 这是我的代码

function prodType() {
    
    $("#productType").change(function(){
        let value = $("#productType").val();
        $.ajax({
            url: "<? echo URLROOT. '/AddProduct'?>",
            type:"GET", //not sure if this should be get or post
            data:{
                "optionValue": value
            },
            success: function(response){
                
            }
        });
    });

我确定它获得了价值,但它没有成功地将它传递给 controller。

这是我的 controller

public function index(){
        $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if($_SERVER["REQUEST_METHOD"]=="POST"){
        ...
    }
    /*If request method == Get, load view */
    else{
        $type = $_POST['optionValue']; //trying to get the value here
        $typeClass = ucfirst($type);
        new Display(new $type);
        var_dump($type); //getting null here
        $this->view('add');
     }
  }

这是我的看法

 <select id="productType" name="type" onChange="prodType();" required>
      <option value="" hidden>Select type</option>
      <option value="DVDType" >DVD</option>
      <option value="BookType" >Book</option>
      <option value="FurnitureType">Furniture</option>
    </select>

如文件所述, $_POST _POST 数组包含“通过 HTTP POST 方法传递给当前脚本的变量”。

因此,您应该将 ajax 调用更改为 POST 请求:

function prodType() {
    
    $("#productType").change(function(){
        let value = $("#productType").val();
        $.ajax({
            url: "<? echo URLROOT. '/AddProduct'?>",
            type:"POST",
            data:{
                "optionValue": value
            },
            success: function(response){
                
            }
        });
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM