简体   繁体   English

使用 AJAX(Laravel) 将数据传递给 php 时出错

[英]Error passing data to php using AJAX(Laravel)

Good afternoon, I am trying to pass data from my form to the controller using Ajax, however I cannot do it correctly, what am I doing wrong?下午好,我正在尝试使用 Ajax 将数据从我的表单传递到控制器,但是我无法正确执行,我做错了什么?

Javascript Javascript

$("#btn_enviar").click(function() {

    title = document.getElementById("title").value;
    url_clean = document.getElementById("url_clean").value;
    content = document.getElementById("content").value;
    CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

    $.ajax({
        url     :  'dashboard/post/{data}',
        type    :  'post',
        dataType:  'json',
        data    :   {'CSRF_TOKEN':CSRF_TOKEN, 'title':title, 'url_clean':url_clean, 'content':content},
        success :   function (data) {
            alert('send');
        },
        error   :   function() {
            alert('error');
        }
    });

 });

Routes路线

<?php

use Illuminate\Support\Facades\Route;



Route::get('/', function () {
    return view('dashboard.posts.posts');
});

Route::resource('dashboard/post','dashboard\PostController');

Route::post('dashboard/post/{data}', 'dashboard\PostController@store');

when I click on the button, the console shows me the following error:当我单击按钮时,控制台显示以下错误:

在此处输入图片说明

This has the validation rules for the submitted data这有提交数据的验证规则

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostPost extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|min:5|max:500',
            'url_clean' => 'required|min:5|max:500',
            'content' => 'required|min:5' 
        ];
    }
}

This is the controller I'm trying to send the data to (PostController)这是我试图将数据发送到 (PostController) 的控制器

<?php

namespace App\Http\Controllers\dashboard;

use App\Post;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\StorePostPost;
use Illuminate\Support\Facades\Route;

class PostController extends Controller
{
    public function index(){

        return view("dashboard.posts.create");
    }

    public function create(){

        return view("dashboard.posts.create");
    }

    public function store(StorePostPost $request){
        
        dd($request->all());

    }
}

On POST route , you don't need to define the parameter {data} , because it pass through POST Request, so change it to :POST route 上,您不需要定义参数{data} ,因为它是通过 POST Request 传递的,因此将其更改为:

Route::post('dashboard/post/', 'dashboard\PostController@store');

And your Ajax :还有你的 Ajax :

$.ajax({
    url     :  '/dashboard/post/',
    type    :  'post',
    dataType:  'json',
    traditional: true,
    data    :   {'CSRF_TOKEN':CSRF_TOKEN, 'title':title, 'url_clean':url_clean, 'content':content},
    success :   function (data) {
        alert('send');
    },
    error   :   function() {
        alert('error');
    }
});

You are using a relative URL.您正在使用相对 URL。 Try url: '/dashboard/post/{data}' with a leading slash尝试url: '/dashboard/post/{data}'带前导斜杠

as the image shown the error the url path dashboard/post/{data} the {data} is a parameter value which have to be passed to the function.如图所示,url 路径dashboard/post/{data}{data}是一个必须传递给函数的参数值。
2) the dashboard/post/{data} is repeating as ' dashboard/post/dashboard/post/{data} ' which you need to set the url : 'dashboard/post/{data}' to url : '/dashboard/post/{data}' and {data} should be a value like object_id or something else. 2) dashboard/post/{data}重复为“ dashboard/post/dashboard/post/{data} ”,您需要将其设置为url : 'dashboard/post/{data}'url : '/dashboard/post/{data}'{data}应该是一个像object_id或其他东西的值。

1- Remove the {data} from the url in ajax (it's not needed there) like: 1- 从 ajax 中的 url 中删除 {data} (那里不需要),例如:

url     :  '/dashboard/post/',

2- as I know, laravel csrf_token field should be _token in the data fields,like: 2-据我所知,laravel csrf_token 字段在数据字段中应该是 _token,例如:

data    :   {'_token':CSRF_TOKEN, 'title':title, 'url_clean'..

Give your full url to ajax url param.将您的完整网址提供给 ajax 网址参数。 You are using resource routes, so in get route, your url will be base_url+/dashboard/post.您正在使用资源路由,因此在获取路由中,您的 url 将是 base_url+/dashboard/post。

In post ajax it is calling your current page url and appending given url path.在 post ajax 中,它调用您当前的页面 url 并附加给定的 url 路径。

Can you please provider is with the code in the store function in the controller?你能请提供者在控制器的商店功能中使用代码吗?

The answer from @sta is correct but probably your controller code does not give the correct response back. @sta 的答案是正确的,但可能您的控制器代码没有给出正确的响应。

Also worth mentioning.也值得一提。 You forget to add the laravel methode.您忘记添加 Laravel 方法。 So you should add '_method' :'POST' to your data object所以你应该添加 '_method' :'POST' 到你的数据对象

And off topic, why should u get all the value out a form via a getelementbyid?题外话,为什么要通过 getelementbyid 从表单中获取所有值? If you Get the naming correctly u can also do it like this:如果您正确获得命名,您也可以这样做:

Let data = New FormData($('#form_id')) ;

Something like this.像这样的东西。 Don't have tested it to be honest.老实说,没有测试过它。

edit: okay so this is how i think you should do it: Routes.php >编辑:好的,所以我认为你应该这样做:Routes.php >

Route::resource('dashboard/post','dashboard\PostController');

the reason i dont include your custom url to store is that in the case you showed you dont even need it.我不包含要存储的自定义 url 的原因是,如果您显示您甚至不需要它。 in the resource there i already a store which you can call by ajax.在资源中,我已经有一个可以通过 ajax 调用的商店。 If you ever need to change the store url use this:如果您需要更改商店网址,请使用以下命令:

Route::resource('dashboard/post','dashboard\PostController',['except'=>['store']]);

Route::post('dashboard/post/{data}', 'dashboard\PostController@store');

here i exclude the store from the resource routes so you don't have 2 routes pointing at the exact same function.在这里,我从资源路由中排除了商店,因此您没有 2 条路由指向完全相同的功能。

PostController.php后控制器.php

    public function store(StorePostPost $request){
        
        logger($request->all();
        return response()->json();

    }

i log you request which will now be found in the file /storage/logs/LOGNAME.log then i send back an empty json response with a 200 status.我记录您的请求,现在可以在文件 /storage/logs/LOGNAME.log 中找到它,然后我发回一个状态为 200 的空 json 响应。 which is default.这是默认的。 so this should come in the succes function.所以这应该出现在成功函数中。

Now your javascript:现在你的javascript:

$("#btn_enviar").click(function() {

    title = document.getElementById("title").value;
    url_clean = document.getElementById("url_clean").value;
    content = document.getElementById("content").value;
    CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

    $.ajax({
        url     :  '/dashboard/post',
        type    :  'post',
        dataType:  'json',
        data    :   {
           '_token':CSRF_TOKEN, 
           '_method':'POST',
           'title':title,
           'url_clean':url_clean,
           'content':content
        },
        success :   function (data) {
            alert('send');
        },
        error   :   function() {
            alert('error');
        }
    });

 });

now if you realy want to pass a parameter to you url by ajax you should use this:现在,如果您真的想通过 ajax 将参数传递给您的 url,您应该使用这个:

        url     :  `/dashboard/post/${data}`,

or或者

        url     :  '/dashboard/post/' + data,

but in this case data is not defined in the code you give so it is kinda obvious why that doesn't work但在这种情况下,数据未在您提供的代码中定义,因此很明显为什么这不起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM