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

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

本文关键字:我的 函数 ajax 控制器 laravel 变量 数组      更新时间:2023-09-26

我有一个ajax函数:

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

工作正常,这是我在控制器中的函数,它被路由到上面的 ajax 调用:

public function updateAssignment()
{
  // Bunch of code here
  return 'hello world';
}

现在我知道无论我返回什么,都将在 jQuery 变量data中,但我想要不止一个"值"。

我将如何返回类似的东西

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

到我在 jQuery 中的data变量,并能够像这样使用它:

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

提前感谢您,感谢您的任何帮助。

在 Laravel 5 中,使用 response() 从 AJAX 调用返回 JSON 对象,如下所示:

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

在你的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
            }
    }