【问题标题】:is there any way to pass vuejs object to laravel controller? [closed]有没有办法将 vuejs 对象传递给 laravel 控制器? [关闭]
【发布时间】:2021-02-17 12:57:45
【问题描述】:

我有一个 Vue 组件,它有一个对象,我想将它发送到 laravel 控制器! 它不仅仅是一个 js 对象!有没有人知道我如何将此对象作为 JSON 发送到 Laravel 控制器?

更新:

我是用 Axios 做的!感谢您的关注。

【问题讨论】:

    标签: javascript php ajax laravel vue.js


    【解决方案1】:

    如果您需要将整个对象作为字段传递,则必须将其作为字符串传递,然后在控制器上使用 json_decode。

    使用 axios 进行请求的示例:

    axios.post("your_endpoint",
    {your_object_field_name: JSON.stringify(your_object)}).then(res => {
    //handle response
    })
    

    在控制器上:

    public function yourControllerMethod(){
       $data = response()->validate('your_object_field_name','required|json'); //validate the field so it is in valid json format
       $jsonArray = json_decode($data); // here you have your json as a php object, pass true as second argument if you want an array (json_decode($data,true))
    }
    

    【讨论】:

      【解决方案2】:

      以下是发送姓名和电子邮件的 POST 示例

         //Variables
          data(){
            return{
              object:{
                 name: null,
                 email: null,
              }
           }
          }
      
          //In methods
          sendPost(){
             axios.post("http://url-route-exemple.com", this.object).then(result => {
               console.log(result.data); //return laravel
             })
          }
      

      这样就可以获取laravel标准(PHP)中的姓名和邮箱数据了

      //In controller.php
      $name = $request->input("name");
      $email = $request->input("email");
      $jsonNameAndEmail = json_encode($request->all());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-18
        • 2021-04-13
        • 1970-01-01
        • 2017-06-19
        • 1970-01-01
        • 1970-01-01
        • 2017-01-30
        • 1970-01-01
        相关资源
        最近更新 更多