我正在尝试从我的 React 组件对 php 文件进行 ajax 调用,我希望 php 文件在其中返回特定的输出,但我却得到了完整的源代码。有人可以帮忙吗?
这就是我的 React 组件。
import React from 'react';
import {Link} from 'react-router';
export default class BikePage extends React.Component {
onFormSubmitSuccess(e) {
e.preventDefault();
$.ajax({
url: 'php/new_user.php',
type: "GET",
success: function(data) {
console.log('success')
console.log(data);
}.bind(this),
error: function(xhr, status, err) {
console.log('error')
}.bind(this)
});
}
render(){
return (
<button onClick={this.onFormSubmitSuccess.bind(this)} >click here</button>
)
}
}
这是我的 php 文件中的内容。
<?php
//Function to check if the request is an AJAX request
$return = 'hello'
echo json_encode($return);
?>
我要测试的只是在我的控制台上获取“Hello”。但是我得到了整个 php 文件。
最佳答案
在您的情况下,您在 PHP 中使用 json_encode()
来获取响应,而不是使用 DataType:json
,您只需要将 DataType 用作 json,例如:
dataType: "json",
你的 json 输出应该是这样的:"message"
修改后的 Ajax:
$.ajax({
url: 'php/new_user.php',
type: "GET",
dataType: "json",
success: function(data) {
console.log('success');
console.log(data); // will print "message"
}.bind(this),
error: function(xhr, status, err) {
console.log('error');
}.bind(this)
});
关于javascript - 从 React 到 PHP 文件的 Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40360766/