我有一个主要用 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/.
因此,虽然此方法有效,但它可能随时停止这样做。
但是如果我运行代码 async [xmlhttp.open("GET", filename, true);],那么下一行将在结果出现之前执行。该值将是未定义的。
让异步 XMLHttpRequest 在这种情况下工作是否可行?在编写一些聪明的 API 之前,我是否应该坚持同步获取值? 我应该用 PHP 编写我的 JS 文件吗? (我希望不会。)
附言:
我不使用任何框架,例如 jQuery。那是一件“宗教”的事情。我想自己完全理解和维护整个代码库。
我阅读了以下问题,但没有回答我的问题:
最佳答案
是的,你需要回电!
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();
关于javascript - 通过 XMLHttpRequest 从 PHP 将 gettext 与 Javascript 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46477165/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我在开发的Rails3网站的一些搜索功能上遇到了一个小问题。我有一个简单的Post模型,如下所示:classPost我正在使用acts_as_taggable_on来更轻松地向我的帖子添加标签。当我有一个标记为“rails”的帖子并执行以下操作时,一切正常:@posts=Post.tagged_with("rails")问题是,我还想搜索帖子的标题。当我有一篇标题为“Helloworld”并标记为“rails”的帖子时,我希望能够通过搜索“hello”或“rails”来找到这篇帖子。因此,我希望标题列的LIKE语句与acts_as_taggable_on提供的tagged_with方法
我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h