【问题标题】:How to pass an array of variables from a laravel controller to my ajax function如何将变量数组从 laravel 控制器传递给我的 ajax 函数
【发布时间】:2016-06-15 12:37:02
【问题描述】:

我有一个 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']); 或类似的东西

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

【问题讨论】:

  • 尝试从您的控制器返回一个 JSON 字符串并使用 data.title 访问各个组件。

标签: javascript php jquery ajax laravel-5


【解决方案1】:

在 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
});

【讨论】:

    【解决方案2】:
        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
                }
        }
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 2019-09-10
      相关资源
      最近更新 更多