如何将变量数组从 laravel 控制器传递到我的 ajax 函数
How to pass an array of variables from a laravel controller to my ajax function
我有一个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
}
}
相关文章:
- 为什么不是'我的函数在解析云代码中工作吗?当我在Angular和Express中测试时,它是有效的
- 使用JAVASCRIPT转换货币.可以't通过我的函数设置转换后的输入文本字段的值
- 为什么我的函数没有被调用呢
- 为什么我的函数没有返回准确的计数
- 我的函数返回“未定义”
- 用我的函数jquery给出数据/参数
- 从未达到我的函数调用-ReactJs 0.12.0
- 我的函数不会返回要保存在数组中的对象
- 为什么点击或更改事件都没有触发我的函数
- 为什么如果我的函数中的范围被 javascript 解释器完全忽略了
- 我的函数调用在回显中不起作用
- 我的函数返回空.为什么
- 我的函数不起作用,Ajax调用,JQuery,调用外部?我不知道
- 如何在我的函数中使用 .bind()
- 在jQuery中,我的函数不起作用
- 为什么不是'我的函数未按预期在文档加载时运行
- 传递的变量不适用于我的函数-Javascript
- jQuery:我的函数需要一个反垃圾邮件
- 为什么不是't调用我的函数
- 为什么我的函数参数说是未定义的