Tag Archives: JQuery

The solution of calling$. Ajax successfully but the success method does not respond

Today, when I was working, I encountered a problem. I used $. Ajax to transfer data to the background, which can operate correctly in the background, but success did not respond, and error responded. After checking the document, I realized that after jQuery version 1.4, all the returned JSON formats must meet the requirements json.org Success can only be called back correctly in the format of, otherwise jQuery will think that it returns an error Here is an example:

JSONObject j = new JSONObject();
j.put("msg","SUCCESS");
PrintWriter out = response.getWriter();
out.write(j.toString());

This is correct. JQuery calls back success

String j = "123";
PrintWriter out = response.getWriter();
out.write(j);

This is wrong, jQuery will think it is wrong

 

Summary of jQuery autocomplete plug-in

Requirement: realize the prompt effect similar to Baidu search, that is, you can filter the options in the drop-down list through keywords

There are ready-made autocomplete plug-ins in layui and iView, but they need to integrate the dependencies related to layui and iView. I just want to realize this function in a simple business environment, and there is no integrated environment in the business framework of the system, so this method has low cost performance.

I found a case of using jQuery for integration on the Internet and studied it by myself. The notes in the original chestnut are not very clear, which is not easy for people like me who have not understood and studied the autocomplete component of jQuery before. Don’t talk too much nonsense. Paste the effect picture first

The above screenshot is an example, which I used for integration in my project. Ajax can achieve real-time access and fixed source array filter values. Next, I will post the codes of the two examples:

The first method is to use source array

    var countries = {
        "AD": "Andorra",
        "A2": "Andorra Test",
        "AE": "United Arab Emirates",
        "AF": "Afghanistan",
        "AG": "Antigua and Barbuda"
        }
    var countriesArray = $.map(countries, function (value, key) { return { value: value, data: key }; });
    $('#autocomplete-ajax').autocomplete({
        lookup: countriesArray,   // If this attribute is written, it means that a fixed array of data is used, even if the serviceUrl attribute is also available, it will not take effect
        lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
            var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
            return re.test(suggestion.value);
        },
        onSelect: function(suggestion) {
            $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
        },
        onHint: function (hint) {
            $('#autocomplete-ajax-x').val(hint);
        },
        onInvalidateSelection: function() {
            $('#selction-ajax').html('You selected: none');
        }
    });

The second way: Ajax real-time access

    var countriesArray = $.map(countries, function (value, key) { return { value: value, data: key }; });

    //jQuery ajax mock,Simulate background processing of incoming requests
    $.mockjax({
        url: '*',
        responseTime: 2000,
        response: function (settings) {
            var query = settings.data.query,
                queryLowerCase = query.toLowerCase(),
                re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi'),
                suggestions = $.grep(countriesArray, function (country) {
                     // return country.value.toLowerCase().indexOf(queryLowerCase) === 0;
                    return re.test(country.value);
                }),
                response = { // Note that the return format must be in this format
                    query: query,
                    suggestions: suggestions
                };

            this.responseText = JSON.stringify(response);
        }
    });
    // Initialize ajax autocomplete:
    $('#autocomplete-ajax').autocomplete({
        serviceUrl: '/autosuggest/service/url',
        // lookup: countriesArray, // This must be commented out, otherwise the countriesArray array in the property will be used instead of taking the ajax request in the serviceUrl
        lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
            var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
            return re.test(suggestion.value);
        },
        onSelect: function(suggestion) {
            $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
        },
        onHint: function (hint) {
            $('#autocomplete-ajax-x').val(hint);
        },
        onInvalidateSelection: function() {
            $('#selction-ajax').html('You selected: none');
        }
    });

In this way, we need to pay attention to the following points:

    1. when using serviceurl, the lookup attribute must be commented out; the serviceurl attribute is configured with the real request path of the background, and the above configuration is to simulate the background processing by using mockjax, and the corresponding mockjax code does not need to be reflected in the program; the format of the data returned by the background must be strictly in accordance with: {“query”: query, “suggestions”: suggestions}, Suggestions is the filtered data, and you can debug the specific format to understand it; </ OL>

The following is my own specific code:


$(function () {
    'use strict';

    // Initialize ajax autocomplete:
    $('#autocomplete-ajax').autocomplete({
        serviceUrl: 'http://127.0.0.1/test/autosuggest/userInfo/4028805e6d5e3155016d637627d80157',
        lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
            var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
            return re.test(suggestion.value);
        },
        onSelect: function(suggestion) {
            $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
        },
        onHint: function (hint) {
            $('#autocomplete-ajax-x').val(hint);
        },
        onInvalidateSelection: function() {
            $('#selction-ajax').html('You selected: none');
        }
    });
    
});

last:

You are welcome to exchange and study with me. Because this article was written after the event, I can’t remember which God’s code was written at that time. The source code has to be written down. The website is as follows: www.jq22.com , the specific use of the case has not been found, the following is the source code link I downloaded before, can be downloaded for free, if there is infringement, please contact to delete.

be careful:

1. When using Ajax dynamic request, the plug-in will pass a query parameter to the background: I use @ requestparam (name = query “, required = false) string query to accept it;

2. When using Ajax dynamic request, the return format is fixed, and the name of the return attribute should not be modified. The return format code is as follows

@Getter
@Setter
@ToString
public class Result1 implements Serializable {

	@ApiModelProperty("Query criteria")
	private String query;
	
	@ApiModelProperty("return output")
	private List<Result12> suggestions;
}

@Getter
@Setter
@ToString
public class Result12 implements Serializable {

	@ApiModelProperty("name")
	private String value;
	
	@ApiModelProperty("key")
	private String data;
}

JQuery is a solution to the disappearance of listening events after adding elements with append

Suppose you want to append an element in the div with ID target
the original listening event format is:

$(".textBox").mouseover(function() {});

To be amended as follows:

$("#target").on("mouseover", ".textBox", function() {});

Add a dynamic box for target ID all the time, not a dynamic box!!! If you really can’t, just let the body go

[jQuery] jQuery operates on JSON strings or JSON objects

preface

Most of the time, you need to convert a JSON string to a JSON object, and then process it in a loop, or convert a JSON object to a JSON string as a parameter and pass it to the relevant interface. Next, we will introduce several conversion methods

Assume that the JSON string is

Var jsonstr = ‘[{“Id”: 1, “title”: “Zhang San”, “sex”: “male”}, {“Id”: 2, “title”: “Li Si”, “sex”: “male”}]’;

Assume that the JSON object is

Var jsonobj = [
{
“Id”: 1,
“title”: “Zhang San”,
“sex”: “male”
},
{
“Id”: 2,
“title”: “Li Si”,
“sex”: “male”
}
]

1、 Convert JSON string to JSON array object

1、eval()

var jsonObj = eval('(' + jsonStr + ')');

2、JSON.parse()

var jsonObj = JSON.parse(jsonStr);

Prev

var jsonObj = JSON.parse(jsonStr);

2、 Convert JSON object to JSON string

JSON.stringify ()

var jsonStr = JSON.stringify(jsonObj);

3、 Loop JSON object

for (var i = 0; i < jsonObj.length; i++) {

    var name= jsonObj[i].Title;

}

 

Solution to report undefined a error when using jquery

When the project uses easyUI, the foreground reports an error, type error: A is undefined. I see that the error location is actually the source code of JQ… It’s impossible. I searched a lot of information on the Internet, but I didn’t solve the problem. After nearly a month’s thinking, I seem to have found the cause of this problem. It may not be right. It only represents personal profile. If there is a positive solution, please let me know. Thank you.

The error screenshot is as follows:

The reasons are as follows: I have such a piece of code in JS:

 $('#cargo_info').datagrid().datagrid('getPager');

Note that this code is not put in any function, nor is it wrapped with $(function () {}). Just this sentence is put directly in JS code. This is all the cases that report this error in my project. My preliminary analysis is because JS thinks that there is no method to call this sentence, so it reports an error.

Solution: wrap the isolated statements in JS with $(function () {}), or write them in a function,

<pre name="code" class="javascript">$(function(){
    $('#cargo_info').datagrid().datagrid('getPager');
})


Like this, you can’t make a mistake at the front desk

Fatal error: Uncaught Error: Call to undefined function mysql_ Connect() problem solving

Fatal error: Uncaught error: Call to undefined function mysql_connect() : Fatal error: Uncaught error: Call to undefined function mysql_connect() when connecting to the database using PHP validation code. This is because the version of PHP you are using does not support the older version of join statement writing. The PHP version used in this study is PHP-7.4.2-NTS-Win32-VC15-x64, and the verification code is:
< ?PHP
the mysql_connect (‘ 127.0.0.1 ‘, ‘runner_db_user’, ‘runner_db_password’)
the OR die (” Could not connect to the database. ‘);
the mysql_select_db (‘ hfjq_race_info ‘);
echo “Connected!” ;
?>
After inquiry, this writing method is the previous version of 5. X, the following code is as follows:
< ?php
$con=mysqli_connect(“127.0.0.1”, “runner_db_user”, “hfjq_race_info”)
OR die(‘Could not connect to database.’);
echo “Connected!” ;
?>
You can connect to the database normally. If you have extension=mysqli, change the semicolon “;” before extension=mysqli. You can connect to the MySQL database normally if you remove it

Traversing the background data to generate tree structure

var getTree=function(treeData,parentId){
var treeArr=[];
for(var i=0; i< treeData.length; i++){
var node=treeData[i];
if(node.sjchannelcode==parentId ){
var newNode={order:node.order,code:node.channelcode,url:node.url,name:node.name,sjchannelcode:node.sjchannelcode,channelcode:getTree(treeData,node.channelcode)};
treeArr.push(newNode);
}
}
return treeArr;
}
// call tree method
var treeArr=getTree(data,sj);
data is the data returned from the background, sj root directory returned by the node parent id

Browser prompt: Source mapping error: request failed with status 404 Source URL: http://xxx.js Source mapping URL: jquery.min.map

Browser Jquery1.9.1 min.js newspaper script error no jquery.min.map file
 
I recently encountered this problem when Browsing personal websites
Let me first say what a Source map file is.
Source map file is after js file is compressed, the variable name of the file replaces the corresponding, variable location and other metadata data file, generally this file and min.js main file are placed in the same directory.
Such as the original variable is the map after compression, compressed by variable substitution rules may be replaced with a, then the source map file will keep a record of the mapping information, so that the benefits of that is to say, at the time of debugging, if there is some JS error, then the browser will by parsing the map file to merge compressed JS, the developers can use the code to debug, uncompressed, this will bring us a lot of convenience!
Solutions:
Remove the sentence “// @sourcemappingURL =jquery.min.map”

 
 

Django + jQuery get data in the form + Ajax send data

1. Method 1: obtain form data through Jquery$("# corresponding form id). SerializeArray (), and directly assign values to $. Ajax data.

.serializearray () method see jQuery ajax-serializearray () method
this method puts back an array of JSON objects.

$("#postSubmit").click(function () {
                    let data = $("#postContent").serializeArray();
                    $.ajax({
                        url: '/decuhub/home-post-ajax',
                        method: 'POST',
                        data: data,
                        async: true,
                        success: function (result) {
                            console.log("post successfully!")
                        }
                    })
                })

2. The method 2: by $(" # corresponding form form id) serializer () to obtain the form data:

$("#postSubmit").click(function () {
                    let data = $("#postContent").serializer();
                    $.ajax({
                        url: '/decuhub/home-post-ajax',
                        method: 'POST',
                        data: data,
                        async: true,
                        success: function (result) {
                            console.log("post successfully!")
                        }
                    })
                })

. Method 3:

is not recommended

$("#postSubmit").click(function () {
                    let postContentForm = $("#postContent").serializeArray();
                    let data = {};
                    $.each(postContentForm, function(){
                        data[this.name] = this.value;
                    })
                    $.ajax({
                        url: '/decuhub/home-post-ajax',
                        method: 'POST',
                        data: data,
                        async: true,
                        success: function (result) {
                            console.log("post successfully!")
                        }
                    })
                })

$.each() reference jQuery. Each ()

Django's request-post gets

<QueryDict: {'csrfmiddlewaretoken': ['vO34OFZtTj2Bp2ARMlXVJxZQb37CyuWR7ywaDC4QaJhHtcxB4xB9fnb2IOnbQ2AR'], 'content': ['asdfsd']}>