简体   繁体   English

jQuery AJAX函数调用

[英]jQuery AJAX function call

I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. 我在jQuery调用AJAX函数时遇到问题,基本上每次用户更改选择框时,我都希望它调用getSubCategories函数,但是由于某种原因,什么也没有发生。 Any ideas? 有任何想法吗?

If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening? 如果我加载页面并在getSubCategories函数内添加console.log,它将对其进行记录,这是否应该发生?

function getSubCategories() {
    var id = $("#category").prop('selectedIndex');
    var selectedCategory = $("#category").val();
    //should change this into a response from AJAX and grab the slug from there, this is fine for now.
    var slugOfCategory = convertToSlug(selectedCategory);
    id++;
    console.log('here');
    $.ajax({
        method: 'GET', // Type of response and matches what we said in the route
        url: '/product/get_subcategories', // This is the url we gave in the route
        data: {
            'id': id
        }, // a JSON object to send back
        success: function(response) { // What to do if we succeed
            $("#sub_category option").remove(); //Remove all the subcategory options
            $.each(response, function() {
                $("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
            });
            $("#category_slug").attr('value', slugOfCategory);
        },
        error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
            console.log(JSON.stringify(jqXHR));
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
    });
}

function getCategories() {
    var id = $("#type").prop('selectedIndex');
    var selectedType = $("#type").val();
    //should change this into a response from AJAX and grab the slug from there, this is fine for now.
    var slugOfType = convertToSlug(selectedType);
    console.log(slugOfType);
    //add one to the ID because indexes dont start at 0 as the id on the model
    id++;
    $.ajax({
        method: 'GET', // Type of response and matches what we said in the route
        url: '/product/get_categories', // This is the url we gave in the route
        data: {
            'id': id
        }, // a JSON object to send back
        success: function(response) { // What to do if we succeed
            $("#category option").remove(); //Remove all the subcategory options
            $.each(response, function() {
                $("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
            });
            $("#type_slug").attr('value', slugOfType);
        },
        error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
            console.log(JSON.stringify(jqXHR));
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
    });
}

function convertToSlug(Text) {
    return Text
        .toLowerCase()
        .replace(/ /g, '_')
        .replace(/[^\w-]+/g, '');
}

$(document).ready(function() {

    var firstCatgegory = $("#category").val();
    var slugOfFirstCategory = convertToSlug(firstCatgegory);
    $("#category_slug").attr('value', slugOfFirstCategory);

    var firstType = $("#type").val();
    var slugOfFirstType = convertToSlug(firstType);
    $("#type_slug").attr('value', slugOfFirstType);

    $("#type").change(getCategories());

    $("#category").change(getSubCategories());
});

Thanks for any help. 谢谢你的帮助。 (Sorry the code is a little messy, i've just been trying to get it to work so far) (对不起,代码有点混乱,到目前为止,我一直在尝试使其工作)

This is due to the fact that the ajax call you are trying to make is asynchronous. 这是由于您尝试进行的ajax调用是异步的。 When you call getSubCategories() it returns undefined which is why your code is not working. 当您调用getSubCategories()时,它返回undefined,这就是您的代码无法正常工作的原因。

To make this work you need to put your code within the success callback function instead. 为此,您需要将代码放入成功回调函数中。

<script>
function getSubCategories()
{
     var id= $("#category").prop('selectedIndex');
     $.ajax({
          method: 'GET',
          url: '/product/get_subcategories',
          data: {'id' : id}, 
          success: function(response){ 
             // DO SOMETHING HERE
          },
          error: function(jqXHR, textStatus, errorThrown) { }
    });
}

$( document ).ready(function() {

    // This is also wrong. Currently you're passing
    // whatever is returned from getSubCategories
    // (which is undefined) as the callback function
    // that the "change" event will call. This instead
    // should be the reference to the function. Which
    // in this case is getSubCategories

    $("#category").change(getSubCategories);
});

Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting. 请将getCategories()getSubCategories()方法放在Change函数中,抱歉,未格式化代码。

<script>
$(document).ready(function(){
$("#category").change(function(){
    getSubCategories();
});
$("#type").change(function(){
    getCategories();
});
});
</script>

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

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