如何使用 Typescript 执行 AJAX 请求?(使用 JSON)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43724081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I do an AJAX request with Typescript? (using JSON)
提问by Ise92
I'm learning AJAX and I'm trying to do an AJAX request with parameters, but I'm having problems to send the JSON data:
我正在学习 AJAX 并且我正在尝试使用参数执行 AJAX 请求,但是我在发送 JSON 数据时遇到了问题:
I'm using Typescript and PHP (with Codeigniter), the idea is to create a Typescript object and send it to the PHP in JSON format. So basically I create an object and use the stringify method that I find on Google to convert this object to JSON (or a string in form of JSON I should say?) and send it to the server with AJAX, but the data is not arriving properly.
我正在使用 Typescript 和 PHP(使用 Codeigniter),想法是创建一个 Typescript 对象并以 JSON 格式将其发送到 PHP。所以基本上我创建一个对象并使用我在 Google 上找到的 stringify 方法将此对象转换为 JSON(或者我应该说的 JSON 形式的字符串?)并使用 AJAX 将其发送到服务器,但数据没有到达适当地。
I used print_r($_POST);
to see what is the server receiving and it shows to me the following:
我曾经print_r($_POST);
看到服务器接收的是什么,它向我显示以下内容:
Array
(
[{"_dificultad_seleccionada":"Normal"}] =>
[0] =>
)
The entire string that I get from stringify is shown as the key and the value is empty.
我从 stringify 获得的整个字符串显示为键,值为空。
I don't understand very well what is happening, isn't stringify the way to convert an object to JSON and send it to the server? Why it isn't sending the object properly?
我不太明白发生了什么,不是将对象转换为 JSON 并将其发送到服务器的方法吗?为什么它没有正确发送对象?
Client code:
客户端代码:
Dificultad.ts(class that I want to send to the server)
Dificultad.ts(我想发送到服务器的类)
class Dificultad {
private _dificultad_seleccionada: string;
constructor (dificultad_seleccionada: string) {
this._dificultad_seleccionada = dificultad_seleccionada;
}
get dificultad_seleccionada(): string {
return this._dificultad_seleccionada;
}
set dificultad_seleccionada(dificultad_seleccionada: string) {
this._dificultad_seleccionada = dificultad_seleccionada;
}
}
Lib.ts(where I declare all const, DOM elements, etc.)
Lib.ts(我在其中声明了所有 const、DOM 元素等)
const BASE_URL: string = window.location.origin + "/Project_name/";
type CallbackFunction = (arg: any, ...args: any[]) => void;
Main.ts(here is where I send the AJAX)
Main.ts(这里是我发送 AJAX 的地方)
$(document).ready(function() {
$( "a#boton_seleccion_dificultad" ).click(function(event) {
event.preventDefault();
if (pasapalabra.gameState == GameState.GAME_STARTING) {
let _dificultad: Dificultad = new Dificultad("Normal");
sendAjaxRequest("POST", "get_dificultad_seleccionada", JSON.stringify(_dificultad), function(response) {
console.log(response);
});
}
});
});
function sendAjaxRequest(_type: string, _url: string, _params: string, _callback: CallbackFunction) {
var request = $.ajax({
type: _type,
url: BASE_URL + _url,
data: _params,
contentType: 'json'
});
request.done(function(res) {
_callback(res);
});
request.fail(function(jqXHR, textStatus) {
console.error(jqXHR)
_callback({ err: true, message: "Request failed: " + textStatus });
});
}
Server code:
服务器代码:
Welcome.php
欢迎.php
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
$this->load->library("grocery_CRUD");
date_default_timezone_set('Europe/Madrid');
$this->load->library('session');
$this->load->helper('url');
$this->load->model("Rol_model");
$this->load->model("Questions_model");
}
public function get_dificultad_seleccionada() {
print_r($_REQUEST); print_r($_POST);
//echo json_encode($dificultad);
}
}
It seems to be a problem with the object conversion that I do with stringify on the client because if I change the ajax call like this, sendind a JSON manually, it works:
我在客户端上用 stringify 进行的对象转换似乎有问题,因为如果我像这样更改 ajax 调用,手动发送一个 JSON,它可以工作:
Main.ts
主文件
sendAjaxRequest("POST", "get_dificultad_seleccionada", {"_dificultad_seleccionada":"Normal"}, function(response) {
console.log(response);
});
It seems that I'm doing something wrong but I have no idea of what could be, how can I send this object to the server in JSON format?
似乎我做错了什么,但我不知道可能是什么,如何以 JSON 格式将此对象发送到服务器?
I want to do an universal function for all AJAX request in my program, but I don't know very well if I'm doing it properly, is the type of the callback function ok? or am I wrong with this?
我想在我的程序中为所有AJAX请求做一个通用函数,但我不太清楚我是否做得正确,回调函数的类型好吗?还是我错了?
Thank you very much for your help.
非常感谢您的帮助。
回答by Ise92
I think I have solved the problem, I'm sending the same data like I did before but now I use contentType: 'json'
to tell the server that I'm sending a JSON and in the server side (PHP) I use the following to get the json: json_decode(file_get_contents('php://input'), true);
我想我已经解决了这个问题,我像以前一样发送相同的数据,但现在我contentType: 'json'
用来告诉服务器我正在发送一个 JSON,在服务器端 (PHP) 我使用以下内容来获取 json :json_decode(file_get_contents('php://input'), true);
Main.ts
主文件
$(document).ready(function() {
$( "a#boton_seleccion_dificultad" ).click(function(event) {
event.preventDefault();
if (pasapalabra.gameState == GameState.GAME_STARTING) {
let _dificultad: Dificultad = new Dificultad("Normal");
sendAjaxRequest("POST", "get_dificultad_seleccionada", JSON.stringify(_dificultad), function(response) {
console.log(response);
});
}
});
});
function sendAjaxRequest(_type: string, _url: string, _params: string, _callback: CallbackFunction) {
var request = $.ajax({
type: _type,
url: BASE_URL + _url,
data: _params,
contentType: 'json'
});
request.done(function(res) {
_callback(res);
});
request.fail(function(jqXHR, textStatus) {
console.error(jqXHR);
_callback({ err: true, message: "Request failed: " + textStatus });
});
}
Welcome.php
欢迎.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->database();
$this->load->library("grocery_CRUD");
date_default_timezone_set('Europe/Madrid');
$this->load->library('session');
$this->load->helper('url');
$this->load->model("Rol_model");
$this->load->model("Questions_model");
}
public function get_dificultad_seleccionada() {
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["_dificultad_seleccionada"];
}
}
Now the server gets the value properly and I supose that now it's getting it in JSON format.
现在服务器正确获取值,我假设现在它以 JSON 格式获取它。