【问题标题】:I need to send a request through JS to a php file via API我需要通过 JS 通过 API 向 php 文件发送请求
【发布时间】:2021-10-01 21:39:24
【问题描述】:

请帮帮我。有两个 php 文件 Data.php 和 Status.php。在 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';
}

【问题讨论】:

  • 到目前为止你做了什么?你能把代码分享给我们,以便我们理解
  • 阅读 AJAX 教程。

标签: javascript php ajax api xmlhttprequest


【解决方案1】:

您需要从第一个 php 向第二个 php 发送 AJAX 调用。
在第一个 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>
?>

然后从下一个 php 文件返回您的内容数据,如下所示。
test2.php

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

?>

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 是的,没错。 fetch 是一种更现代的方法。您使用 fetch('url').then(function(){console.log('a');}).then(function(){console.log('success');}).catch(function(){console.log('boo')}) 而不是 XMLHttpRequest。
    猜你喜欢
    • 2018-07-26
    • 1970-01-01
    • 2012-03-15
    • 2017-09-14
    • 2021-05-03
    • 2021-03-29
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    相关资源
    最近更新 更多