简体   繁体   English

我需要通过 JS 发送请求到 php 文件 via API

[英]I need to send a request through JS to a php file via API

Help me please.请帮帮我。 There are two php files Data.php and Status.php.有两个php文件Data.php和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)在zip字段中输入数据时,需要向Data.php文件发送请求,如果zip可用,则将数据发送到Status.php,在此处输入代码,解析字段中的响应。下面我给出一个js 示例和 Data.php,Status.php 我将不胜感激)

 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'; }

You need to send an AJAX call from the first php to second php.您需要从第一个 php 向第二个 php 发送一个 AJAX 呼叫。
Include following script inside first php file.在第一个 php 文件中包含以下脚本。
test1.php test1.php

<?php 
// other content
<script>
(function() {
  var httpRequest;
  document.getElementById("ajaxButton").addEventListener('click', makeRequest);

  function makeRequest() {
    httpRequest = new XMLHttpRequest();

    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    httpRequest.onreadystatechange = alertContents;
    httpRequest.open('GET', 'test2.php');
    httpRequest.send();
  }

  function alertContents() {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        alert(httpRequest.responseText); // your response
      } else {
        alert('There was a problem with the request.');
      }
    }
  }
})();
</script>
?>

Then return your content data from the next php file as follows.然后从下一个 php 文件中返回你的内容数据,如下所示。
test2.php test2.php

<?php 
    $x = "content data";
    echo $x;

?>

For more details about AJAX, follow below link https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started有关 AJAX 的更多详细信息,请点击以下链接https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started

javaScript Code 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);
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我需要在 Node JS 中通过 email 发送加密的 pdf 文件 - I need to send an encrypted pdf file via email in Node JS 我可以将发布请求发送到 js 文件而不是 php 吗? - Can I send a post request to a js file instead of php? 尝试发送请求时出现“ 405方法不允许”错误。 通过JS提取API到PHP文件 - “405 Method Not Allowed” error while trying to send req. via JS fetch API to PHP file 如何通过ajax请求将字符串和文件一起发送到php文件? - How to send a string along with file via ajax request to a php file? 如何将文件上传请求从 Next.js API 传递到另一个 API? - How do I pass through a file upload request from a Next.js API to another API? 如何在 PHP 中向通过 javascript fetch API 发出的请求发送响应? - How to send a response in PHP to a request made through the javascript fetch API? 我需要在 Ajax 中传递什么才能通过 SFTP (JS + PHP) 上传文件 - What do i need to pass in Ajax to upload a file via SFTP (JS + PHP) 如何将文件作为有效负载发送到 Node.js 中的 API 请求? - How can i send a file as a payload to a API Request in Node.js? 如何通过 request.json 将 FORMDATA() 发送到 php 文件 - how to send FORMDATA() through request.json to php file 将POST请求从js文件发送到php文件 - Send POST request from js file to php file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM