Эти jQuery
функция, которую Вы чаще всего вызываете с $
, берет второй аргумент, названный контекстом, который является, "какой элемент DOM объекта jQuery должен я выполнять в поиске". Большую часть времени Вы опускаете этот аргумент, таким образом, значения по умолчанию контекста к текущему документу HTML. Когда Ваш код выполняется в iframe, значениях по умолчанию документа к документу того iframe. Но можно легко захватить документ для одного из других кадров.
, Например, помещает это в myFrame.html
, и это удалит все h1 элементы из кадра с blah.html
в нем. Заметьте второй аргумент $
, который является выражением, которое захватывает скучный кадр из важного кадра:
<html>
<head>
<script type="text/javascript" src="/javascripts/jquery.js"></script>
<script type="text/javascript">
function doIt() {
$('h1', window.parent.frames[0].document).remove()
}
</script>
</head>
<body>
<h1>My Frame</h1>
<a href="#" onclick="doIt()">Do It</a>
</body>
</html>
I've only just started to work with Wicket myself, but I would simply mount the resource as a shared resource with its own URL. You just override init()
in your Application
and register the resource with
getSharedResources().add(resourceKey, dynamicImageResource);
Then, you mount it as a shared resource with
mountSharedResource(path, resourceKey);
For some reason, that I still do not completely grasp, you have to prepend the class name of the application to the resource key you pass to mountSharedResource()
.
Let's add a fully working example for some bonus votes! First create an empty Wicket template with
mvn archetype:create -DarchetypeGroupId=org.apache.wicket \
-DarchetypeArtifactId=wicket-archetype-quickstart \
-DarchetypeVersion=1.4.0 -DgroupId=com.mycompany \
-DartifactId=myproject
Then, override the init()
method in WicketApplication
by adding:
@Override
protected void init() {
final String resourceKey = "DYN_IMG_KEY";
final String queryParm = "id";
getSharedResources().add(resourceKey, new Resource() {
@Override
public IResourceStream getResourceStream() {
final String query = getParameters().getString(queryParm);
// generate an image containing the query argument
final BufferedImage img = new BufferedImage(100, 100,
BufferedImage.TYPE_INT_RGB);
final Graphics2D g2 = img.createGraphics();
g2.setColor(Color.WHITE);
g2.drawString(query, img.getWidth() / 2, img.getHeight() / 2);
// return the image as a PNG stream
return new AbstractResourceStreamWriter() {
public String getContentType() {
return "image/png";
}
public void write(OutputStream output) {
try { ImageIO.write(img, "png", output); }
catch (IOException ex) { /* never swallow exceptions! */ }
}
};
}
});
mountSharedResource("/resource", Application.class.getName() + "/" +
resourceKey);
}
The little dynamic PNG resource just writes the query parameter on black background. Of course, you can access your DB or do whatever you like to produce the image data.
Finally, execute mvn jetty:run
, and you will be able to access the resource at this URL.
Вот мой пример, который делает то же самое для динамически скомпилированного списка идентификаторов, обслуживаемых как общий ресурс со статическим URL-адресом ..
public class WicketApplication extends WebApplication {
...snip...
@Override
protected void init() {
//Spring
addComponentInstantiationListener(new SpringComponentInjector(this));
//Register export lists as shared resources
getSharedResources().putClassAlias(ListInitializer.class, "list");
new ListInitializer().init(this);
}
И мой ListInitializer, который регистрирует ресурсы как DBNAME_SUBSELECTION1 ( 2/3 / ..)
public class ListInitializer implements IInitializer {
public ListInitializer() {
InjectorHolder.getInjector().inject(this);
}
@SpringBean
private DatabankDAO dbdao;
@Override
public void init(Application application) {
//For each databank
for (Databank db : dbdao.getAll()) {
String dbname = db.getName();
//and all collection types
for (CollectionType ct : CollectionType.values()) {
//create a resource
Resource resource = getResource(dbname, ct);
//and register it with shared resources
application.getSharedResources().add(this.getClass(), dbname + '_' + ct, null, null, resource);
}
}
}
@SpringBean
private MyApp MyApp;
public Resource getResource(final String db, final CollectionType collectionType) {
return new WebResource() {
@Override
public IResourceStream getResourceStream() {
List<String> entries = MyApp.getEntries(db, collectionType.toString());
StringBuilder sb = new StringBuilder();
for (String entry : entries) {
sb.append(entry.toString());
sb.append('\n');
}
return new StringResourceStream(sb, "text/plain");
}
@Override
protected void setHeaders(WebResponse response) {
super.setHeaders(response);
response.setAttachmentHeader(db + '_' + collectionType);
}
}.setCacheable(false);
}
}
Мне очень жаль, но мне кажется, что я больше не могу найти учебник, который использовал, чтобы настроить это, но должно быть очевидно, как это связано с приведенным выше примером и может быть настроено для выполнения то же самое для изображений ... (Извините за скудное объяснение, если все еще неясно, я могу вернуться и отредактировать свой ответ)