ajax - Dart Adaj错误

标签 ajax http-post dart

我正在尝试使用Dart的adaj库:

import 'dart:html';
import 'dart:convert';
import "package:adaj/adaj.dart" as http;

void main() {
    Map data = {
        "email": "john.smith@example.com",
        "password": "12345"
    };

    var url = "http://localhost:8080/myapp/signin";

    http.post(url, data).fail(onFail).always(alwaysHandler).done(onSuccess).go();
}

void onFail(String failMsg) {
    window.alert("Error! " + failMsg);
}

void alwaysHandler(dynamic response) {
    window.alert("Always executing");
}

void onSuccess(Map json) {
    window.alert("The returned json is : " + json['answer']);

    if(json == 1)
        window.alert("You are signed in!");
    else
        window.alert("Sign in failed. Check credentials.");
}

当我运行此代码时,我希望从服务器返回一个值“1”,然后将显示一个警告框,并显示文本“您已登录!”。在里面。

相反,当我运行此代码时,我收到一条警告:“错误!1”,然后收到第二条警告,显示“始终在执行:1”。

关于错误从何而来的任何想法?当我在Firebug中运行此命令时,我看到来自服务器的HTTP POST响应为“1”,这意味着它肯定是客户端错误。

最佳答案

发生这种情况是因为adaj尝试将响应视为 map 。您可以在source中看到:

Map result = request.responseText.isEmpty ? {} : JSON.decode(request.responseText);

由于1无法强制进入 map ,因此会引发错误。

您可以通过返回类似{ "code": 1 }的方法来解决此问题,该方法可以正确转换为Map。

您还必须将onSuccess回调参数更改为Map类型,并将alwaysHandler参数类型更改为dynamic,因为如果发布成功,则将使用Map调用always回调,如果发生错误则将使用String调用。

以下是您应该拥有的最终代码:
import 'dart:html';
import "package:adaj/adaj.dart" as http;

void main() {
    Map data = {
        "email": "john.smith@example.com",
        "password": "12345"
    };

    var url = "http://localhost:8080/myapp/signin";

    http.post(url, data).fail(onFail).always(alwaysHandler).done(onSuccess).go();
}

void onFail(String failMsg) {
    window.alert("Error! " + failMsg);
}

void alwaysHandler(dynamic response) {
    window.alert("Always executing");
}

void onSuccess(Map json) {
    window.alert("The returned json is :  ${json['answer']}");

    if(json['answer'] == 1)
        window.alert("You are signed in!");
    else
        window.alert("Sign in failed. Check credentials.");
}

使用此代码,我收到以下警报:
"Always executing"
"The returned json is: 1"
"You are signed in!"

关于ajax - Dart Adaj错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20790710/

相关文章:

php - 如何使用 PHP 和 Smarty 同时获取数据并将其显示在浏览器中?

jquery - 处理表单时显示微调器 gif

Javascript 发布 HTML 表单

java - HttpPost 和线程异常

jquery - AngularJS 和 Ajax 帖子 - 如何触发 ajax 错误(而不是成功)回调

function - 如何将函数传递给其他类并将函数的响应返回给 flutter 中的主类

android - “package :flutter/src/widegets/text. dart”:断言失败:第 235 行 pos 15: 'data ! = NULL ':不正确

javascript - JQuery Ajax 用 Jquery 函数替换项目

javascript - 在头文件顶部导航中使用 AJAX Search Lite 插件 - WordPress

modal-dialog - Bootjack Modal生成异常:类 'TransitionEvent'没有实例getter 'relatedTarget'