gpt4 book ai didi

ajax - 在没有 View 的情况下仅在 FW1 中使用 Controller

转载 作者:行者123 更新时间:2023-12-04 23:26:41 24 4
gpt4 key购买 nike

我有一个 Ajax 请求,它将一些数据发送到一个页面,并根据数据是否被保存而期望返回一个真值或假值。在我的 Controller 中,我做所有事情并将内容设置为 true 或 false 值。我真的不想创建 View 只是为了输出 1 个变量,所以我想知道是否有一种方法可以不必使用 View 而只使用 Controller 来输出简单的字符串。

最佳答案

我相信您不能完全禁用 View ,但有一个非常简单的解决方法:您可以创建一个 View 并将其用于许多操作。

假设我们已经创建了 View views/main/ajax.cfm ,里面会是什么?显然,最简单的方法是:

<cfoutput>#HTMLEditFormat(rc.response)#</cfoutput>

我个人喜欢返回 JSON,它允许我拥有 status字段,加上数据(如果需要)。这样我的观点是这样的:
<cfheader name="Content-Type" value="application/json" />
<cfoutput>#SerializeJSON(rc.response)#</cfoutput>

无论如何,现在在我们的行动中,我们需要做这样的事情:
// prevent displaying the layout
request.layout = false;

// force special view
variables.fw.setView("main.ajax");

// init response (according to the choice made earlier)
rc.response["status"] = "OK";
rc.response = "";

这还有一个问题。有时您不希望直接访问 AJAX 页面(例如在浏览器中打开),或者反之亦然——希望在需要时进行一些调试。

有一个很酷的 helper isAjax在 CFWheels 框架中,很容易移植到 FW/1。它可以像向 Controller 添加这样的方法一样简单:
/*
* Check if request is performed via AJAX
*/
private boolean function isAjax() {

return (cgi.HTTP_X_REQUESTED_WITH EQ "XMLHTTPRequest");

}

实际上,上面的设置代码也是我的应用程序中的辅助方法:
/*
* Set up for AJAX response
*/
private struct function setAjax() {

// prevent displaying the layout
request.layout = false;

// force special view
variables.fw.setView("main.ajax");

local.response["status"] = "OK";

return local.response;

}

所以在我的操作代码中,整个检查看起来像这样,非常紧凑和方便:
if (isAjax()) {
rc.response = setAjax();
}
else {
return showNotFound();
}

希望这可以帮助。

关于ajax - 在没有 View 的情况下仅在 FW1 中使用 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11821089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com