如何获取Laravel 4中从Angular传递的FormData的值

How to get value of FormData that is passed from Angular in Laravel 4?

本文关键字:Angular 的值 FormData 中从 何获取 获取 Laravel      更新时间:2024-01-28

我使用angular上传图像(同时上传其他数据),并使用angular服务传递到Laravel的路由,所有这些都使用javascript中的FormData函数。这是我上传的代码(在coffeescript中):

            tag = null
            if $('span.tag').length > 0
                tag = $('span.tag').map(->
                    $.trim @innerHTML
                ).get().join(",")
            fd = new FormData()
            fd.append "title", $scope.title
            fd.append "subtitle", $scope.subtitle
            fd.append "date", $scope.date
            fd.append "time", $scope.time
            fd.append "category", $scope.category
            fd.append "content", $scope.content
            fd.append "tag", $scope.tag
            fd.append "caption", $scope.caption
            fd.append "active", !$scope.active
            if $scope.file
                fd.append "image", $scope.file
            alert fd
            UploadService.news.save fd
            , ( (response) ->
                alert response.data
            )

我的UploadService就是这样,指向Laravel的路线:

app.factory "UploadService", ["$resource", ($resource) ->
    news: $resource("upload/news")
    member: $resource("404/upload/member")
]

我的问题是,我无法读取从FormData传递到Laravel的数据,即使是这样:

return Response::json(['data' => $_POST['title']]);

return Response::json(['data' => Input::get['title']]);

将返回undefined index 'title',我的代码的哪一部分是错误的?谢谢你的帮助。

这是我刚刚做的一个测试,目的是检查FormData是否有效:

Route::post('test', function() {
    Log::info(Input::all());
    return Response::json(['data' => Input::all()]);
});

然后跟踪日志:

php artisan tail

你应该得到这样的东西:

[2014-04-04 20:10:19] server.INFO: {"_token":"MIFCleetMa029UGpUcvXUhawmVdJyl65zYBmXDHM","id":"1""first_name":"Antonio Carlos","last_name":"Ribeiro"}

这是我的(香草)Javascript代码,应该也能在Angular应用程序中正常工作。

var form = document.getElementById('form1');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://development.consultoriodigital.net/test', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(xhr.responseText);
    }
}
xhr.send(formData);

您还必须将表单放回控制台。

form1表单可以包含任意数量的表单输入,这无关紧要。

关于这条线的注意事项:

return Response::json(['data' => Input::get['title']]);

应该是

return Response::json(['data' => Input::get('title')]);