普通网友 2019-10-20 05:02
浏览 54

如何在Laravel上使用Ajax?

I made a JavaScript code to process my request search request using Ajax. So thus, my code is defined as the following:

if(document.getElementById('category')){
    document.getElementById('category').addEventListener('click', () => {
        var query = document.getElementById('category').value;
        if(query !== ''){
            var httpRequest = new XMLHttpRequest();
            httpRequest.open('GET', "http://127.0.0.1:8000/category/fetch");
            httpRequest.send();
            console.log(httpRequest);
        }
    });
}

where my category is from my form:

<div class="col s12 m8 l8">
    <input type="text" name="category" value="{{old('category') ?? $book->category ? $book->category->name : ''}}" class="input-field validate" id="category">
    <input type="hidden" name="category_id" value="{{ $book->category ? $book->category->id : ''}}">
</div>

and my get request refers to my function:

public function fetch(Request $request){
    dd("You hit me: ".$request);
    $category = Category::where('name', 'like', $request['category'])->first();
    return response()->json($category);
}

but back to my JavaScript, Why my get request is not hitting my fetch function? while doing it manually on browser it gives me the result and also my console is giving me this kind of result:

response: "<script> Sfdump = window.Sfdump || (function (doc)"

like the image below. Ajax Request

  • 写回答

1条回答 默认 最新

  • bug^君 2019-10-20 07:19
    关注

    Great question!

    To provide a little bit of context, Laravel is built in part off of Symfony, another PHP framework, and shares a lot of packages. One such package is called var-dumper, and it's what enables the dd helper function in Laravel.

    Take a look at this sample, taken straight from the dd helper package:

    //...
    <script>
    Sfdump = window.Sfdump || (function (doc) {
    //...
    

    Source

    Look familiar? If you viewed the source of the page that you're saying works manually in the browser, you'll see the exact same code. Turns out what you're seeing in your AJAX request is correct after all -- it's just raw HTML content that hasn't been transformed by the browser.


    If you want to output non-dd content (as in, not marked up with script tags and other fancy-ness), try using PHP's built-in die('Your message') method (only for debugging!) or just stick to Laravel's built in response()->json methods.

    Hope that helps!

    评论

报告相同问题?