zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Retrieve data using AJAX requests.


slug: 57
title: Using Ajax to Fetch Data
date: 2021-03-19 13:01:00
updated: 2021-12-01 09:03:03
categories:
- Technology
tags:
- js
- ajax

Fetching data through Ajax using jQuery is a convenient way. I have created a local data.json file and used the get method to request the data. Below is a portion of the code:

// Ajax request to fetch data
function picShow(){
    var str = '';
    $.ajax({
        url:'./js/data.json',
        type:'get',
        dataType:'json',
        success:function(data){
            console.log('success')
        },
        error: function() {
            console.log('error')
        }
    })
}
picShow();

However, there is a drawback to this approach. It cannot be previewed locally because browsers prohibit clients from directly accessing local data. This can be considered a cross-origin issue, but it is also done to ensure user security. Of course, this is frustrating for front-end developers!

The solution is actually quite simple. By using a node server and running it locally with live server, Ajax can fetch the data. There are also other better solutions, such as running it directly on a server or using JSONP, etc.

If you are not familiar with live server, you can search for it on Baidu. It is also a useful technique.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.