My method is to use the Accept header to determine the request type.
For example, for the same url, /products:
When requesting, set accept to text/html and the method to get, then an html page will be returned.
If accept is application/json and the method is get, a product list in json format is returned. /products?limit=20 will return the first 20 items in the list.
If accept is application/json and the method is put, a product will be added.
That's probably it, control the result of the request through url, http method, accept,
In this way, the server can make a judgment based on the request header, similar to this:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special ajax here */
// send JSON data
} else {
// send html data
}
My method is to use the Accept header to determine the request type.
For example, for the same url,
/products
:When requesting, set accept to text/html and the method to get, then an html page will be returned.
If accept is application/json and the method is get, a product list in json format is returned.
/products?limit=20
will return the first 20 items in the list.If accept is application/json and the method is put, a product will be added.
That's probably it, control the result of the request through url, http method, accept,
It would be easier if the backend used the
express
framework.Most JavaScript frameworks will include a request header identifying Ajax when sending an Ajax request:
If not, you can set one manually, in jQuery it is like this:
In this way, the server can make a judgment based on the request header, similar to this: