dsjq6977 2014-11-30 08:09
浏览 27
已采纳

Laravel 4无法将输出从jQuery路由到Controller

This is a Laravel 4 image manipulation project. I am going round in circles trying to solve this conundrum, which I am sure has an elementary solution. The user chooses some images, previews them and then clicks to upload.

The problem is that handleForm's output (the FormData object) does not get routed to the ImageController for the rest of the image handling. On clicking nothing happens. Debugging shows that the FormData object (data in xhr.send(data)) contains the images that the user specified.

The relevant bits: 1 The user clicks to upload.

<input type="button" value="Upload" id="go"/>

  1. In the jQuery the .click event starts handleForm function:

$("#go").on("click", handleForm); 
  1. In handleForm the storedFiles array contains the users chosen images after previewing them.

function handleForm(e) {
        e.preventDefault();
        var data = new FormData();
        
        
        for(var i=0, len=storedFiles.length; i<len; i++) {
            data.append('files', storedFiles[i]);             
        }
        
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'upload', true);
        
        xhr.onload = function(e) {
            if(this.status == 200) {
                console.log(e.currentTarget.responseText);  
                alert(e.currentTarget.responseText);
            }
        }
        xhr.send(data);
    }
  1. In Routes

Route::post('upload', array(
    'as' => 'upload',
    'uses' => 'ImageController@upload'
    
    ));
  1. In ImageController:

<?php

    class ImageController extends BaseController {

    public function upload(){   
        
        $files = Input::all('files');

        $gallery =  str_random(12);
           

        foreach ($files as $file) {

            $validation = Image::validateImage(array('file'=> $file));

            ...................

This is the first time I have tried to incorporate jQuery in Laravel and I need some help!

</div>
  • 写回答

1条回答 默认 最新

  • donglian5309 2014-12-06 22:20
    关注

    The answer in this case was to change the jQuery to make files into array files[] like:

    for(var i=0, len=storedFiles.length; i<len; i++) {
                data.append('files[]', storedFiles[i]);             
            }
    

    I couldn't find this solution anywhere despite hours of searching, it was just a trial and error approach.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序