乐闻世界logo
搜索文章和话题

What 's the point of the X- Requested -With header?

1个答案

1

X-Requested-With header is typically used to identify the method (e.g., Ajax) employed to initiate an HTTP request. Its most common application is to identify XMLHttpRequest requests (Ajax requests). Developers commonly leverage this header to determine whether the request was initiated by JavaScript, thereby deciding whether to return a full page or a response containing only the necessary data.

Usage Scenario Example

Suppose we are developing a webpage that needs to validate data without refreshing the page when users interact with a form. In this case, we can use Ajax to initiate an asynchronous request to the server, including the header X-Requested-With: XMLHttpRequest in the request.

Server-side code checks this header:

python
# Assuming this is server-side code written with Python Flask from flask import request @app.route('/verify', methods=['POST']) def verify(): if request.headers.get('X-Requested-With') == 'XMLHttpRequest': # Handle Ajax request data = request.form['data'] # Perform data validation is_valid = validate_data(data) return jsonify({'valid': is_valid}) else: # Handle regular request return render_template('error.html'), 400

In this example, the server first checks whether the X-Requested-With header is present and its value is XMLHttpRequest to determine if it is an Ajax request. If so, the server executes validation logic and returns the validation result in JSON format; otherwise, it returns an error page.

Through this approach, the X-Requested-With header enables us to distinguish request types, facilitating a more dynamic and responsive web experience.

2024年7月26日 21:40 回复

你的答案