You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决CORS跨域报错并实现Ionic-Select获取PHP接口数据

解决CORS拦截问题并在Ionic Select组件中展示数据

问题根源

从http://localhost:8100访问http://localhost/phpfile/leave-option.php时被CORS策略拦截,核心原因是实际请求(如GET)的响应中缺少Access-Control-Allow-Origin头。当前PHP代码仅在OPTIONS预检请求中设置了该头,但浏览器会校验所有跨域请求的响应头,因此需要补充配置。

修正后的PHP后端代码

在所有允许的请求类型中添加CORS头,确保OPTIONS预检和实际请求都能通过校验:

<?php
// 处理OPTIONS预检请求
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    $allowed_origins = array('http://localhost:8100');
    $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
    if (in_array($origin, $allowed_origins)) {
        header("Access-Control-Allow-Origin: " . $origin);
    }
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization");
    exit;
}

// 为GET/POST请求添加CORS头
$allowed_origins = array('http://localhost:8100');
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
if (in_array($origin, $allowed_origins)) {
    header("Access-Control-Allow-Origin: " . $origin);
}

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pis";
$connect = new mysqli($servername, $username, $password, $dbname);

// 查询请假类型数据
$query = "SELECT id, TypeofLeave AS name FROM leave_info";
$result = mysqli_query($connect, $query);

$options = [];
while ($row = mysqli_fetch_assoc($result)) {
    $options[] = $row;
}

// 返回JSON格式数据
header('Content-Type: application/json');
echo json_encode($options);
?>

Ionic前端实现(Angular版本)

1. 创建数据服务

在项目中新建leave.service.ts,封装接口请求:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LeaveService {
  private apiUrl = 'http://localhost/phpfile/leave-option.php';

  constructor(private http: HttpClient) { }

  getLeaveOptions(): Observable<any[]> {
    return this.http.get<any[]>(this.apiUrl);
  }
}

2. 页面组件逻辑

在目标页面的.ts文件中(如leave.page.ts),调用服务获取数据:

import { Component, OnInit } from '@angular/core';
import { LeaveService } from '../services/leave.service';

@Component({
  selector: 'app-leave',
  templateUrl: './leave.page.html',
  styleUrls: ['./leave.page.scss'],
})
export class LeavePage implements OnInit {
  leaveOptions: any[] = [];
  selectedLeaveId: string = '';

  constructor(private leaveService: LeaveService) { }

  ngOnInit() {
    this.loadLeaveOptions();
  }

  loadLeaveOptions() {
    this.leaveService.getLeaveOptions().subscribe(
      data => {
        this.leaveOptions = data;
      },
      error => {
        console.error('获取请假类型失败:', error);
      }
    );
  }
}

3. 页面模板渲染ion-select

在页面的.html文件中(如leave.page.html),使用ion-select组件展示数据:

<ion-header>
  <ion-toolbar>
    <ion-title>请假申请</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-item>
    <ion-label>请假类型</ion-label>
    <ion-select [(ngModel)]="selectedLeaveId" placeholder="请选择类型">
      <ion-select-option *ngFor="let option of leaveOptions" [value]="option.id">
        {{ option.name }}
      </ion-select-option>
    </ion-select>
  </ion-item>
  <p *ngIf="selectedLeaveId">已选类型: {{ leaveOptions.find(o => o.id == selectedLeaveId)?.name }}</p>
</ion-content>

4. 导入HttpClient模块

确保在app.module.ts中导入HttpClientModule,否则无法发起HTTP请求:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    // 其他导入项
    HttpClientModule
  ],
  // 其他配置
})
export class AppModule { }

验证步骤

  1. 启动PHP后端服务(确保leave-option.php可正常访问)
  2. 启动Ionic项目(ionic serve)
  3. 打开页面查看ion-select是否正常加载请假类型选项

内容的提问来源于stack exchange,提问作者Karl Francis Lopez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 23:20:02