我需要通过 JS 通过 API 向 php 文件发送请求 [英] I need to send a request through JS to a php file via API
本文介绍了我需要通过 JS 通过 API 向 php 文件发送请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请帮帮我.有两个 php 文件 Data.php 和 Status.php.在zip字段中输入数据时,需要向Data.php文件发送请求,如果zip可用,将数据发送到这里的Status.phpenter代码,解析字段中的响应. 下面我给出一个js 示例和 Data.php、Status.php我将不胜感激)
Help me please. There are two php files Data.php and Status.php. When you enter data in the zip field, you need to send a request to the Data.php file, and if zip is available, send the data to Status.phpenter code here and parse the response in the field.Below I will give a js example and Data.php, Status.php I will be grateful for the help)
function ajax(params) {
var xhr = new XMLHttpRequest();
var url = params.url || '';
var body = params.body || '';
var success = params.success;
var error = params.error;
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(body);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status === 200 && typeof success === 'function') {
success(xhr.response);
} else if (xhr.readyState === 4 && xhr.status !== 200 && typeof error === 'function') {
error(xhr.response);
}
};
xhr.onerror = error || null;
}
//Data.php
<?php
header('Content-Type: application/x-www-form-urlencoded');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['zip'])) {
$zip = filter_var($_POST['zip'], FILTER_VALIDATE_REGEXP, array('options'=>array('regexp'=>'/^[0-9]{5}/')));
if ($zip) {
$status = (int) $zip < 33333 ? array('zip' => $zip, 'state' => 'OH', 'city' => 'NEWTON FALLS') : array('zip' => $zip, 'state' => 'CA', 'city' => 'BEVERLY HILLS');
echo json_encode($status);
} else {
echo 'error';
}
} else {
echo 'error';
}
//Status.php
<?php
header('Content-Type: application/x-www-form-urlencoded');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['zip'])) {
$zip = filter_var($_POST['zip'], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^[0-9]{5}/')));
if ($zip) {
$status = (int) $zip < 33333 ? 'allowed' : 'blocked';
echo $status;
} else {
echo 'error';
}
} else {
echo 'error';
}
推荐答案
javaScript 代码
const data = { name: 'scott' }; // data for post
fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json', // type
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
这篇关于我需要通过 JS 通过 API 向 php 文件发送请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文