简体   繁体   English

如何将变量数组从laravel控制器传递给我的Ajax函数

[英]How to pass an array of variables from a laravel controller to my ajax function

I have an ajax function: 我有一个ajax函数:

  $.get('/updateAssignment', {title: title, id: id, class: subject, date: date, description: description}, function(data)
  {

    window.location.hash = data;

  });

And it works fine, this is my function in my controller that is routed to the above ajax call: 而且工作正常,这是我控制器中的函数,该函数被路由到上述ajax调用:

public function updateAssignment()
{

  // Bunch of code here

  return 'hello world';

}

Now I know that whatever I return, will be in the jQuery variable data , but I want more than one "value". 现在我知道无论返回什么,都将在jQuery变量data ,但是我想要多个“值”。

How would I return something like 我该如何退货

return array('title' => $title, 'description' => $description, etc...) 

to my data variable in jQuery and be able to use it like: 到我在jQuery中的data变量,并能够像这样使用它:

$('h2').val(data['title']); Or anything similar 或类似的东西

Thank you in advance, I appreciate any help. 在此先感谢您,感谢您的帮助。

In Laravel 5, use response() to return a JSON object from an AJAX call, like this: 在Laravel 5中,使用response()从AJAX调用返回JSON对象,如下所示:

return response(['title' => $title, 'description' => $description]);

In your Javascript, you would then access this data using object notation, so: 然后,在Javascript中,您将使用对象表示法访问此数据,因此:

$.get("URL", function(data){
    var title = data.title;
    var description = data.description;
    // Etc, etc
});
    public class AssignmentViewModels
    {
        public string title { get; set; }
        public string id { get; set; }
        public string class { get; set; }
        public string date { get; set; }
        public string description { get; set; }
    }


    public JsonResult updateAssignment(string title, string id, string class, string date, string description)
    {
        var model = new AssignmentViewModels();// if you have a list of data return, make "List<AssignmentViewModels>()" ,& in Ajax sucess method, make a foreach loop & collect the data.
        model = repository._update(title,id,class,date,description);//return updated data
        return Json(model, JsonRequestBehavior.AllowGet);
    }


    var URL = ResolvedUrl.replace('ActionName', 'updateAssignment').replace('ControllerName', 'YourController');
    var data = { title: title, id: id, class: subject, date: date, description: description };
    $.get(URL, data, function (result) {
            if ($('#h2')[0]) {
                $('#h2').val(result.title);// no need to use JSON.parse
            }
    }

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

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