Cannot have ajax working in my joomla module

2019-09-02 17:51发布

问题:

I'm quite new to joomla development and I'm following a tutorial on how to use AJAX capability in my newly created module.

Basically, in my tmpl/default.php I have:

<script>
function runButton() {
  alert("clicked");
  var url='http://127.0.0.1:4444/getData';
  var request = new Request({
                  url: url,
                  method:'get',
                  onSuccess: function(responseText){
                    document.getElementById('fields-container').innerHTML=  responseText;
                  }
                }).send();
</script>
<?php
  defined('_JEXEC') or die('Restricted access');
?>
<input type="button" value="Click Here for Ajax Call" onClick="runButton()",1000);"/>
  <div id="fields-container">
</div>

When I click on the button, the "run" method is called, but I have the following error in Chrome debugger:

OPTIONS http://127.0.0.1:4444/getData Resource failed to load

The process listening on port 4444 is a proxy that will enable the cross domain ajax calls from within my module. I have thte same issue if I specify 'http://localhost:4444/getData'

Any idea ?

UPDATE

This seems to be linked to theb fact cross port http query is not enabled (even on the same host). Any workaround ?

回答1:

You're using defined( '_JEXEC' ) or die( 'Restricted access' ); which usually restricts ajax.

If you haven't already, you will need to use define('_JEXEC', 1);

Notice that you need to use define, not defined

Please also make sure that this code comes first, before the ajax script.