我想知道在特定页面上执行java脚本代码的最佳方法是什么.
让我们假设我们有一个基于模板的网站,内容集的重写规则,jquery可用,它基本上是这样的:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
...
include $content;
..
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
内容'info'包含一个按钮,我们希望在点击时发生某些事情,当您悬停文本字段时,内容'alert'应该作为消息提供.
触发这些操作的最佳方法是什么,而不会遇到错误,因为找不到该对象?
选项一:使用 window.location.pathname
$(document).ready(function() {
if (window.location.pathname == '/info.php') {
$("#button1").click(function(){'
//do something
})
}else if(window.location.pathname == '/alert.php'){
$("#mytextfield").hover(){
alert('message');
}
}
Run Code Online (Sandbox Code Playgroud)
选项二:检查元素是否存在
$(document).ready(function() {
if ($("#button1").length > 0) {
$("#button1").click(function(){'
//do something
})
}else if ($("#mytextfield").length > 0){
$("#mytextfield").hover(){
alert('message');
}
}
Run Code Online (Sandbox Code Playgroud)
选项三:在加载的模板中包含脚本
//stands for itself
Run Code Online (Sandbox Code Playgroud)
他们是更好的解决方案吗?或者我必须与这些解决方案中的一个相处?
我们非常感谢您的体验,用法或与此主题相关的任何链接.
//编辑:
我可能选择了一个不好的例子,实际的代码可能是:
mCanvas = $("#jsonCanvas");
mMyPicture = new myPicture (mCanvas);
Run Code Online (Sandbox Code Playgroud)
如果mCanvas未定义,则myPicture构造函数获取canvas元素的上下文,并抛出错误.
几天前,我开始使用Google App Engine和Google Cloud Endpoints开发移动应用后端.本教程将介绍如何自动生成端点,以及Android的客户端库.
所以我们有我们的实体:
@Entity
public class Person implements IsSerializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private String name;
//...
}
Run Code Online (Sandbox Code Playgroud)
这个类的端点:
@Api(name = "personendpoint")
public class PersonEndpoint {
@ApiMethod(name = "getPerson")
public Person getPerson(@Named("id") Long id) {
...
Run Code Online (Sandbox Code Playgroud)
此外,使用生成的Android端点库(使用REST API)我想在服务器上添加用户界面,使用Google Web Toolkit(GWT)构建.但是我应该如何操作服务器端的日期?我可以看到不同的方法......
选项A1:在GWT中添加RPC服务
public interface PersonServiceAsync {
void insertPerson(Person person, AsyncCallback<Person> callback);
}
@RemoteServiceRelativePath("api")
public interface PersonService extends RemoteService {
public Person insertPerson(Person person);
}
public class PersonServiceImpl …Run Code Online (Sandbox Code Playgroud) 我正在尝试发送跨域域并添加自定义"授权"标头.请参阅下面的代码.
错误:
XMLHttpRequest无法加载{url}.请求标头字段Access-Control-Allow-Headers不允许授权.
function loadJson(from, to) {
$.ajax({
//this is a 'cross-origin' domain
url : "http://localhost:2180/api/index.php",
dataType : 'json',
data : { handler : "statistic", from : from, to : to
},
beforeSend : setHeader,
success : function(data) {
alert("success");
},
error : function(jqXHR, textStatus, errorThrown) {
alert("error");
}
});
}
function getToken() {
var cookie = Cookie.getCookie(cookieName);
var auth = jQuery.parseJSON(cookie);
var token = "Token " + auth.id + ":" + auth.key;
}
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', getToken());
} …Run Code Online (Sandbox Code Playgroud) 由于jQuery ajax不适用于CORS/IE,我正在使用XDomainRequest其他服务器来检索数据.工作很好,但我想发送一些标题('Authentification','content-type').
是否有机会在XDomainRequest中添加/更改标头?
或者有人知道解决方法吗?
我的网络服务器上有一个REST服务,用php编写.我想知道,什么是最好的身份验证(除了基本的http访问身份验证).我听说过基于令牌的身份证,并且想问一下是否有人可以解释主要步骤.
客户端:Android /浏览器; 服务器:Apache,PHP5
是的,关于这一点有很多主题,但我仍然没有得到它:
我准备了两个jsfiddle:
有什么不同?有很多答案,但我的例子显示相同的输出.所以这些答案中的一些可能是错误的!?
"它允许一个人在一堆元素上调用一个插件或一个事件,然后将相同的功能或事件应用于所有这些元素" - >工作与" return this同样!"
"它允许你链接多个功能" - >在这里相同
"允许你执行以下操作:$("mySelector").foo().show();" - >我还是可以这样,当我回到'这个'
我还创建了另一个jsfiddle,在我看来 - 如果你将代码包装成$("mySelector").foo().show();:
Chrome控制台显示的输出也相同!
那有什么区别?
你怎么用
<item android:drawable="@drawable/ic_launcher" android:state_activated="true"/>
Run Code Online (Sandbox Code Playgroud)
应用程序中的列表视图项目也应该在设备<11上运行?
由于activated_state 在HC之前不可用,我只能想到两个肮脏的解决方法:
Activity.ListAdapter但任何一个都令人满意.(getListView().setChoiceMode(...)没有效果,......)
还有其他想法吗?
我如何修复破损的符号链接?/删除'死'文件?
上下文:由于我在我的一个本地测试服务器上搞砸了我的php.ini配置,所以我决定重新安装基本的web服务器.(apache2,php5,..)
问题:安装后/etc/apache2/php5/php.ini完全缺失,/ etc/apache2/php5/conf.d是一个'破损的符号链接',我想.
错误:安装期间:Not replacing deleted config file /etc/php5/apache2/php.ini
那么这些"破碎的符号链接"是什么?我可以使用'ls/dir'找到它们,它们用红色着色:)我试过"rm/etc/php5 -R -f"?但它不起作用......我应该如何摆脱php.ini'僵尸文件'?我想要的只是一个新的php5安装.
我正在尝试使用JAX-RS(Jersey)构建JSON RESTful Web服务.我也在使用Maven来构建App.
我的第一个方法是
@Path("/Person")
public class PersonService {
@GET
public String getPersonService() {
Personperson= new Person();
person.setLocationCode("MEL");
person.setName("Johannes");
return person.getName();
}
}
Run Code Online (Sandbox Code Playgroud)
在pom.xml-> clean install + Run On Server之后它工作,输出就像execpted一样.但我想使用JAXB来获取JSON格式的Person及其所有属性:
@Path("/Person")
public class PersonService {
@GET
public Person getPersonService() {
Personperson= new Person();
person.setLocationCode("MEL");
person.setName("Johannes");
return person;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我补充道
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.8</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
到我的pom文件.其他lib文件(例如jackson-cors-asl-1.7.1.jar,jackson-jaxrs-1.7.1.jar,jaxb-impl,...)也可以在生成的war文件中找到. //编辑:它还下载了stax-api-1.0.1.jar和stax-api-1.0-2.jar这两个文件之一似乎让错误发生
错误: 但是调用/ Person(或任何其他服务)会导致错误:
javax.servlet.ServletException: Servlet.init() for servlet CloudAPIService threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
com.sap.security.auth.service.webcontainer.internal.Authenticator.invoke(Authenticator.java:147)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
com.sap.core.tenant.valve.TenantValidationValve.invokeNextValve(TenantValidationValve.java:169)
com.sap.core.tenant.valve.TenantValidationValve.invoke(TenantValidationValve.java:84)
com.sap.core.js.monitoring.tomcat.valve.RequestTracingValve.invoke(RequestTracingValve.java:27)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) …Run Code Online (Sandbox Code Playgroud) 我正在尝试替换一个字符串,例如:
Hello, my name is ${name}. I am ${age} years old.
Run Code Online (Sandbox Code Playgroud)
和
Hello, my name is Johannes. I am 22 years old.
Run Code Online (Sandbox Code Playgroud)
变量存储在 HashMap 中。到目前为止我的代码:
private void replace() {
HashMap<String, String> replacements = new HashMap<String, String>();
replacements.put("name", "Johannes");
replacements.put("age", "22");
String text = "Hello, my name is {name}. I am {age} years old.";
Pattern pattern = Pattern.compile("\\{(.+?)\\}");
Matcher matcher = pattern.matcher(text);
StringBuilder builder = new StringBuilder();
int i = 0;
while (matcher.find()) {
String replacement = replacements.get(matcher.group(1));
builder.append(text.substring(i, matcher.start()));
if …Run Code Online (Sandbox Code Playgroud) 再一个关于LocalServices的问题.在onDestroy()之后,如何(重新)绑定到现有服务?
问题:
我绑定了一个服务并从一个Activity启动服务.我将可运行的对象发布到Binder,用于在UI上进行回调(更新进度条).当我关闭这个Activity时,OS可以结束生命周期并销毁Activity,调用onDestroy(),对吗?我模拟了这个,在onPause()方法中调用finish().所以一旦我重新启动Activity,如何再次绑定到SAME服务?我认为服务是Singelton,但是当我试图重新绑定时,我得到另一个绑定器参考.所以binder.callbackHandler.post(binder.progressHandler);仍然引用旧的binder/callback/progressHandler,而不是我的新引用.甚至再次调用服务的构造函数!
是否有任何解决方案可以使用进度条,通过服务中的回调对象进行更新(正常工作).Closing/onDestroy()活动.回来,继续进度吧?
我的代码非常大,但重新创建了Szenario:
public class MyService extends Service {
private final LocalBinder binder = new LocalBinder();
public class LocalBinder extends Binder implements TestRunServiceBinder {
private Handler callbackHandler;
private ServiceStartActivity.RunOnServiceProgress onProgress;
@Override
public void setActivityCallbackHandler(Handler messageHandler) {
callbackHandler = messageHandler;
}
@Override
public void setServiceProgressHandler(RunOnServiceProgress runnable) {
onProgress = runnable;
}
public void doSomething(){
_doSomething();
};
private void _doSomething(){
while(...){
//do this a couple of times (could take up to 10min)
binder.callbackHandler.post(binder.progressHandler);
wait()
}
}
}
Run Code Online (Sandbox Code Playgroud)
_ …
E/dalvikvm(5717): Unable to open stack trace file '/data/anr/traces.txt': Is a directory
Run Code Online (Sandbox Code Playgroud)
关于LogCat中的这个ErrorMessage,我想删除traces.txt目录并创建一个文件.我在哪里可以找到它?
我正在使用flask、sqlalchemy 和marshmallow 编写一个简单的REST API。默认情况下,模型始终序列化为具有按字母顺序排列的属性的 json。
有没有办法用棉花糖指定 json 属性的顺序?
例如:
class Sample(db.Model):
y = db.Column(db.String(256), primary_key=True)
x = db.Column(db.String(256))
def __init__(self, y, x):
self.x = x
self.y = y
class SampleSchema(Schema):
y = fields.Str()
x = fields.Str()
@app.route('/sample')
def get_sample():
dummy = Sample("MyY", "MyX")
logger.info(dummy)
schema = SampleSchema()
return jsonify(schema.dump(dummy).data)
Run Code Online (Sandbox Code Playgroud)
返回
{
"x": "MyX",
"y": "MyY"
}
Run Code Online (Sandbox Code Playgroud)
但我希望
{
"y": "MyY",
"x": "MyX"
}
Run Code Online (Sandbox Code Playgroud)
我知道 json 是一个无序集合,这对客户端来说无关紧要。但是,它更多地用于开发和漂亮打印期间的调试目的。所以我希望有一个框架让我定义属性的顺序。