Vanilla AJAX请求通过了Laravel验证,但控制器中的值不可用

时间:2018-04-09 23:24:42

标签: javascript php ajax laravel

我尝试使用AJAX(vanilla JS)向Laravel 5.5控制器提交表单,该控制器将搜索Amazon产品API。

AJAX正在提交正确的关键字和类别输入,请求传递的表单请求同时需要关键字和类别,但关键字和类别在控制器中不可用。我确实得到了控制器的占位符响应。

开发者工具中Chrome浏览器网络标签中的请求有效负载显示AJAX正在发送正确的字词。

HTML表单

<form method="POST" action="http://local.example.com/api/products/search" accept-charset="UTF-8" id="product-search-form">
    <input name="_token" type="hidden" value="qcXA3xVIoltX9tSpeJeWuKVa3alUkq1p5tuIlKJ5">
    <div class="form-group">
        <label for="keywords" class="required">Keywords</label> 
        <input id="keywords" placeholder="Enter keywords" aria-required name="keywords" type="text">
    </div>
    <div class="form-group ">
        <label for="category">Category</label> 
        <select id="category" name="category">
            <option selected="selected" value="">Choose a category...</option>
            <option value="All">All</option>
            <option value="Apparel">Apparel</option>
            <option value="Books">Books</option>
            <option value="DVD">DVD</option>
            <option value="Electronics">Electronics</option>
            <option value="Music">Music</option>
            <option value="Software">Software</option>
            <option value="SoftwareVideoGames">SoftwareVideoGames</option>
            <option value="Toys">Toys</option>
            <option value="VideoGames">VideoGames</option>
            <option value="UnboxVideo">Video on Demand</option>
        </select>
    </div>
    <div>
        <button id="search-products-submit" type="submit" class="button-primary">Search</button>
    </div>
</form>

提交时的JavaScript AJAX发布请求

function getProducts(keywords, category) {
    let path = "api/products/search";

    let searchTerms = {
        keywords: keywords,
        category: category,
        _token: getCsrfToken(),
    };

    ajaxPostRequest(path, showProducts, searchTerms);
}

AJAX请求

function ajaxPostRequest(path, callback, formId) {
    return ajaxRequest("POST", path, callback, formId);
}

function ajaxRequest(method, path, callback, data = null) {
    let xhr = new XMLHttpRequest();
    let url = getFullUrl(path);

    addEventListeners(xhr);

    xhr.open(method, url, true);

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            let parsedResponse = JSON.parse(xhr.responseText);
            callback(parsedResponse);
        }
    };

    setRequestHeaders(xhr, method);

    xhr.send(JSON.stringify(data));
}

AJAX请求有效负载

{
    keywords: "aaa",
    category: "All", 
    _token: "qcXA3xVIoltX9tSpeJeWuKVa3alUkq1p5tuIlKJ5"
}

表格请求

class SearchProductsFormRequest extends Request
{
    /**
     * 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(): array
    {
        return [
            'keywords' => 'required',
            'category' => 'required'
        ];
    }
}

控制器

/**
 * @param SearchProductsFormRequest $request
 * @return JsonResponse
 */
public function create(SearchProductsFormRequest $request): JsonResponse
{
    if ($request->has('keywords')) {
        \Log::info('Got keywords');
    } else {
        \Log::info('Did not get keywords');
    }

    if ($request->has('keywords')) {
        \Log::info('Got category');
    } else {
        \Log::info('Did not get category');
    }

    \Log::info(print_r($request, true));
    \Log::info('keywords: ' . $request->input('keywords'));
    \Log::info('category: ' . $request->input('category'));
    return response()->json([
        'name' => 'Abigail',
        'state' => 'CA'
    ]);
}

记录输出

[2018-04-08 19:26:15] local.INFO: Did not get keywords
[2018-04-08 19:26:15] local.INFO: Did not get category
[2018-04-08 19:26:15] local.INFO: keywords:
[2018-04-08 19:26:15] local.INFO: category:

console.log服务器响应(用于测试的虚拟数据)

{name: "Abigail", state: "CA"}

因此控制器被调用并响应,但无法读取输入数据。

setRequestHeaders()

function setRequestHeaders(xhr, method) {
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.setRequestHeader("X-CSRF-TOKEN", getCsrfToken());

if (method === 'GET') {
    xhr.setRequestHeader('Content-Type', 'application/json');
} else {
    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
}

1 个答案:

答案 0 :(得分:-1)

因为您没有将该值传递给控制器​​,所以它为您记录了正确的输出。

这是您提出请求的地方,您在代码中明确地将data = null:

mongoDB.collection('mycol', (err, collection) => {            
    if (err) throw err;            
    collection.find({dept: {$elemMatch:{$in : ['tech']}}}).toArray((err, docs) => {
        console.log(docs);
    });
});

传递正确的参数,你会没事的