简体   繁体   中英

Select2 AJAX is not working

Here is the web method, which I use before for another thing, and it works:

[WebMethod]
public static string GetTests()
{
    return GetData().GetXml();
}

public static DataSet GetData()
{
    DataSet ds = new DataSet();
    BusinessLayer.StudentsController oStudent = new BusinessLayer.StudentsController();
    oStudent.Action = "page";
    oStudent.PageIndex = 0;
    oStudent.PageSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PageSize"].ToString());
    DataTable dt1 = oStudent.Select();
    DataTable dt2 = dt1.Copy();
    dt2.TableName = "Students";
    ds.Tables.Add(dt2);
    DataTable dt = new DataTable("PageCount");
    dt.Columns.Add("PageCount");
    dt.Rows.Add();
    dt.Rows[0][0] = oStudent.PageCount;
    ds.Tables.Add(dt);
    return ds;
}

JavaScript:

$('#selectDynamic1').select2({
    placeholder: "Search for a movie",
    minimumInputLength: 1,
    multiple: true,
    ajax: { 
        url: "Default.aspx/GetTests",
        type: 'POST',
        params: {
            contentType: 'application/json; charset=utf-8'
        },
        dataType: 'json',
        data: function (term, page) {
            return JSON.stringify({ q: term, page_limit: 10 });
        },
        results: function (data) {
            return {results: data};
        },
    },
    formatResult: formatResult,
    formatSelection: formatSelection,
    /*initSelection: function(element, callback) {
        var data = [];
        $(element.val().split(",")).each(function(i) {
            var item = this.split(':');
            data.push({
                id: item[0],
                title: item[1]
            });
        });
        //$(element).val('');
        callback(data);
    }*/
});


function formatResult(node) {
   alert('');
   return '<div>' + node.id + '</div>';
};

function formatSelection(node) {
    alert('');
    return node.id;
};

Please help, GetTests is not even firing, I want to bring the student through SQL then fill the select2.

First, you shoul ry to change the HTTP verb to GET , as you are not posting data to the server, you want to get data from it:

ajax: {
    ...
    type: 'GET',
    ...
}

Secondly, you are expecting JSON from the server, but in the GetData method, you are creating an XML document - at least the code conveys this. This may be one cause, why your code does not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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