通过 XMLHttpRequest 从 PHP 使用 gettext 和 Javascript

2024-04-22

我有一个主要用 PHP 编写的应用程序。翻译是使用 gettext() 完成的。

有一个小的 JavaScript 部分也包含要翻译的字符串。 我使用 XMLHttpRequest 编写了这个简单但有效的方法:

function gettext(string_to_translate) {
    var filename = get_php_script_folder() + 'gettext.php?string_to_translate=' + string_to_translate;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", filename, false);
    xmlhttp.send();
    if (xmlhttp.status === 200) {
        var translated_string = xmlhttp.responseText;
        return translated_string;
    } else {
        console.log("Error while translating " + string_to_translate + " Status " + xmlhttp.status);
        return string_to_translate; //Just give the original string.
    }

}

php 文件也很简单:

require_once '../../default.php'; //configures gettext, session management, etc.
//TODO: support for ngettext might be added.
$string_to_translate = filter_input(INPUT_GET, 'string_to_translate', FILTER_SANITIZE_STRING);
$translated_string = gettext($string_to_translate);
echo $translated_string;

在 JavaScript 中我只是调用:

var input_box_form_default_reason = gettext("Vacation");
document.getElementById('input_box_form_reason').value = input_box_form_default_reason;

如果我同步调用此函数 [xmlhttp.open("GET", filename, false);] Firefox/Chrome 会警告我:

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

因此,尽管此方法有效,但它可能随时停止。

但是,如果我运行异步代码 [xmlhttp.open("GET", filename, true);],那么下一行将在结果出现之前执行。该值将是未定义的。

使异步 XMLHttpRequest 在这种情况下工作是否可行?我是否应该坚持同步获取值,直到编写出一些巧妙的 API 为止? 我应该用 PHP 编写 JS 文件吗? (我希望不是。)

PS:

  1. 我不使用任何像 jQuery 这样的框架。那是“宗教”的事情。我想自己完全理解和维护整个代码库。

  2. 我读了以下问题,但没有回答我的问题:

    • JavaScript 中的翻译就像 PHP 中的 gettext 一样? https://stackoverflow.com/questions/2400106/translation-in-javascript-like-gettext-in-php

    • JavaScript 中的 PHP Gettext,不适用于外部 JS 文件 https://stackoverflow.com/questions/41612768/php-gettext-in-javascript-not-working-in-extern-js-file

    • 在Poedit中提取javascript gettext? https://stackoverflow.com/questions/35406246/extract-javascript-gettext-in-poedit

    • 如何将 gettext 字典中的术语输入 JavaScript? https://stackoverflow.com/questions/21008743/how-do-i-feed-terms-from-a-gettext-dictionary-into-javascript

    • 带有 gettext 和 .po 文件的 javascript i18n https://stackoverflow.com/questions/10151284/javascript-i18n-with-gettext-and-po-files(断开的链接)


是的,您需要回电!

function gettext(string_to_translate, obj, callback)
... //your original xmlhttprequest
xmlhttp.callback = callback;, add a callback to the xmlhttp

//set the readystate event that listens to changes in the ajax call
xmlhttp.onreadystatechange = function()
{
    //target found and request complete
    if (this.status === 200 && this.readyState == 4) {
        //send result to the callback function
        this.callback(obj, this.responseText);
    } else {
        console.log("Error while translating " + string_to_translate + " Status " + xmlhttp.status);
        this.callback(obj, string_to_translate);
    }
}

//callback function specific for this case.
function setValue(obj, value)
{
   obj.value = value;
}

调用这个:

gettext("Vacation", document.getElementById('input_box_form_reason'), setValue);

带回调的扩展ajax函数

function ajax(url, method, json, callBack)
{
	//it supports get and post
	//returns parsed JSON, when json is set to true. | json accessible via this.JSON in the callBack
	//a callback can be attached where the this refers to the xmlHTTP
	//supply an url like you would in a get request: http://www.example.com/page.php?query=1
	//start the request with xmlDoc.fire.
	
	var xmlDoc = new XMLHttpRequest
	xmlDoc.JSON = json ? true : false;
	xmlDoc.error = true;
	xmlDoc.errorMessage = "";	
	xmlDoc.errorObj = {"error" : xmlDoc.error, "object" : "XMLHttpRequest", "message" : xmlDoc.errorMessage, "url" : url, "sync" : true, "method" : (method ? "POST" : "GET")};
	xmlDoc.url = url
	xmlDoc.method = method ? "post" : "get";
	
	xmlDoc.preserveWhiteSpace = true;

	if (method == "post")
	{
		xmlDoc.pUrl = url; 
		xmlDoc.pArg = "";
		if (url.match(/\?/)) //we need to filter out the arguments since the are send seperately. 
		{
			var splitted = url.split(/\?/);
			xmlDoc.pUrl = splitted[0];
			xmlDoc.pArg = "";
			for (var i = 1; i < splitted.length; i++)
			{
				xmlDoc.pArg += splitted[i];	//prevent additional questionmarks from being splitted.				
			}					
			
		}
		
		xmlDoc.open.apply(xmlDoc, ["post", xmlDoc.pUrl , true]); //set up the connection
		
		xmlDoc.setRequestHeader("Content-type", "application/x-www-form-urlencoded ; charset=UTF-8");
	}
	else
	{
		//get request, no special action need, just pass the url
		this.xmlDoc.open("get", url, true); //true for async
	}

	xmlDoc.onreadystatechange = readyStateXML.bind(xmlDoc, callBack);
	xmlDoc.setRequestHeader("Pragma", "no-cache");
	xmlDoc.setRequestHeader("Cache-Control", "no-cache, must-revalidate");
	
	xmlDoc.fire = fireXmlRequest; //set up fire function.
	
	return xmlDoc;
}

function fireXmlRequest()
{
	if (this.method == "post")
	{
		this.send(this.pArg); //post
	}
	else
	{
		this.send(null); //get
	}
}

function readyStateXML(callBack)
{
	if (this.readyState == 4)
	{
		//request completed, now check the returned data
		//We always assume that a request fails.
		if (this.errorMessage == "XML Not loaded." || this.errorMessage == "")
		{
			this.error = false; //set error to false, request succeeded.
			this.errorObj.error = false;			

			if (!this.responseXML && !this.JSON)
			{
				this.error = true;
				this.errorMessage = "invalid XML.";
				this.errorObj.error = this.error;
				this.errorObj.message = this.errorMessage;				
			}
			
			if (this.error == false)
			{
				this.xmlData = this.responseXML;
				
				if (this.JSON)
				{
					try
					{
						this.JSON = JSON.parse(this.responseText);
					}
					catch(err)
					{
						//JSON couldn't be parsed
						this.error = true;
						this.errorMessage = err.message + "<br />" + this.responseText;
						this.errorObj.error = this.error;
						this.errorObj.message = this.errorMessage;		
					}
				}
				
			}
			
			//404 or 400, not found error
			if (this.status == "400" || this.status == "404" || this.status == 400 || this.status == 404)
			{
				this.error = true;
				this.errorMessage = "404: The requested page isn't found.";
				this.errorObj.error = this.error;
				this.errorObj.message = this.errorMessage;				
			}
			else if(this.status == "500")
			{
				this.error = true;
				this.errorMessage = "500: Internal server error.";
				this.errorObj.error = this.error;
				this.errorObj.message = this.errorMessage;				
			}

			if (typeof(callBack) != "undefined")
			{
				callBack.call(this); //pass the xmlDoc object to the callBack
			}
		}
		else
		{
			alert("Error \n" + this.errorMessage);
			if (typeof(callBack) != "undefined")
			{
				callBack.call(this);
			}
		}
			
	}
	else
	{
		this.error = true;
		this.errorMessage = "XML Not loaded.";
		this.errorObj.error = this.error;
		this.errorObj.message = this.errorMessage;		
	}
}

//to use
ajx = ajax("index.php?query=1", "post", true, false, function(){/*callback*/});
   console.log(ajx);
   ajx.fire();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 XMLHttpRequest 从 PHP 使用 gettext 和 Javascript 的相关文章

  • 封装的闭包与类?

    我是 JS 来自 C etc 的新手 我突然想到闭包似乎是比类更简单 更方便的处理封装的方法 这段代码似乎给出了一种处理封装的简单方法 function addProperty o var value o get function retu
  • 如何在D3中导入json数据?

    如何在D3中导入json文件 I did d3 json temp json 但是我如何在进一步的代码中访问这个数据集呢 到目前为止我已经尝试过 var data d3 json temp json 但使用 data data 在其余代码中
  • JS 是否支持使用键函数而不是比较器进行排序?

    JavaScript 的array sort https developer mozilla org en US docs Web JavaScript Reference Global Objects Array sort Syntax方
  • Postman如何发送请求? ajax,同源策略

    我发现了这个非常有用的 Chrome 扩展程序 名为 Postman 这是一个非常有用的扩展 特别是当您正在编写 RESTful 应用程序时 我感到困惑的一件事是这个插件 扩展如何能够在不同的域上成功发送 POST 请求 我尝试像这样使用
  • 这段php代码安全吗?

    我知道我应该使用准备好的语句 但我的下一个项目将使用准备好的语句 我只需要完成这个简单的小应用程序 所以我的问题是 以下代码片段安全吗 我使用了 htmlentities 以及 mysql real escape string 因为我认为这
  • MagicSuggest动态ajax源码

    我在用着魔法建议 https github com nicolasbize magicsuggest对于自动完成输入文本 自动完成提要非常大 因此我无法完整下载它 在他们的示例中 他们提供了以下代码 脚本语言 document ready
  • PHP PDO 与 mysql*() 的安全优势

    使用 PHP PDO 代替 mysql connect 等有任何安全优势吗 不会 与 MySQL 扩展相比 PDO 没有任何安全优势 墨菲定律告诉我们的除外 该定律对两者都适用 两者都会通过转义相同的字符来保证输入安全 然而 PDO 还有其
  • 如何将 !important 添加到 CSS-in-JS (JSS) 类属性?

    我正在尝试使用一些 CSS in JS 类这个答案 https stackoverflow com questions 54525334 how can i change the label size of a material ui te
  • 在 JavaScript 中给变量字符串加上引号

    我有一个 JavaScript 变量 var text http example com 文本可以是多个链接 如何在变量字符串周围放置 例如 我希望字符串看起来像这样 http example com var text http examp
  • 获取发送 cURL 请求的用户的 IP 地址

    我想获取使用 php 中的 cURL POST 方法向我的服务器发送请求的用户的 IP 地址 我正在开发一个 Flight API 我将使用 cURL POST 方法获取请求 我必须获取客户端的 IP 地址并验证他的 IP 地址是否可用 如
  • 尝试利用?

    我看到我的 nopCommerce 网站记录了以下搜索 ADw script AD4 alert 202 ADw script AD4 我有点好奇他们想要完成什么 我搜索了一下 似乎是ADw script AD4 以 UTF7 编码为
  • (jQuery) 在 cookie 中单击时保存复选框状态

    关于此功能有很多主题 但我似乎无法让它工作 我在谷歌上搜索了这个具体案例 有一堆链接让我来到这里 但奇怪的是我似乎无法让它们工作 我所做的唯一工作如下 http dl dropbox com u 2238080 a old z htm ht
  • Laravel项目部署到Cpanel时出现404错误如何解决?

    我正在尝试将我的 laravel Laravel Framework 7 28 3 部署到 Cpanel 但出现 404 错误 我将项目上传到 public html 修改了 index php 文件以指向正确的文件 如下所示 我认为ind
  • 针对 Woocommerce 中多个产品类别计数的 ajax 添加到购物车的 JS 警报

    在 Woocommerce 中 当达到特定产品类别的购物车中的产品的特定数量时 我尝试显示 JavaScript 甜蜜警报 并在达到二级类别的产品的特定数量时显示另一个警报 商品通过 AJAX 添加到购物车 这就是我想使用 JavaScri
  • 在 WCF 服务上的 AJAX 发出 REST 请求期间启用 CORS 中的 OPTIONS 方法

    我花了7个小时绞尽脑汁想弄清楚这个问题 我在整个网络上进行了搜索 但没有运气 我有一个 Angular 应用程序正在向 WCF 命令行托管服务应用程序发出请求 我设法通过使用这两个类来实现 CORS public class CustomH
  • 监听鼠标事件……除了 div 的溢出:滚动滚动条?

    关于如何监听 mousedown 的任何建议 document exceptdiv 的溢出 滚动滚动条 我不确定滚动条是什么元素is为了参考它 您可以使用以下命令自行检查目标 document on mousedown function e
  • 如何解析使用YUI数据源返回的NULL值

    我正在使用 YUI 数据表和数据源来渲染我的项目之一中的数据 返回的数据恰好为NULL YUI数据源无法解析它 下面是数据源和数据表的声明代码 为了便于阅读 我将每个声明分开 列说明声明 var columnDescription key
  • Dojo 是否可以与其他 JS 框架结合?

    我们使用 Dojo 1 9 3 作为构建单页面应用程序的 JS 框架 然而 我们在 Dojo 的怪癖上花费了太多时间 因此即使是简单的任务也需要很长时间才能实现 由于缺乏适当的文档 我们经常不得不求助于阅读源代码 然后实施解决方法 我觉得如
  • JavaScript 有内置的 stringbuilder 类吗?

    I see a few 代码项目解决方案 http www codeproject com KB scripting stringbuilder aspx 但是JavaScript中有常规的实现吗 如果您必须为 Internet Explo
  • Material-UI 中 IconButton 的悬停效果

    图标按钮悬停 https i stack imgur com lsYHX png 这是我正在使用的 Material UI 中的 iconButton 正如您所看到的 当您将鼠标悬停在图标上时 图标周围有一个轻微的灰色边框 禁用此功能的属性

随机推荐