使用 AJAX 执行CakePHP JavaScript

nfeuvbwi  于 2022-11-12  发布在  PHP
关注(0)|答案(4)|浏览(226)

我在视图中有一个JavaScript,但是在用 AJAX 加载了不同的内容之后,它就不再执行了,所以我想把它放在视图的<head>中,这样就可以与AJAX隔离,而不必把它放在一个文件中,因为它使用的是控制器中的PHP数组。我该怎么做呢?有没有一种方法可以用CakePHP的方式编写JavaScript代码,并像JavaScript文件一样将其设置为inline false?
看起来即使是放在head中的JavaScript代码也不会在 AJAX 中执行,那么我应该怎么做呢?我应该把JavaScript相关的div放在内容div之外还是怎么样?
这是我的看法:

<script>
    var geocoder, lat, lng;
    function initialize() {
        var location = <?php echo "\"" . $location . "\""?>;
        location = location.replace(/\+/g, ' ');
        document.getElementById("address").innerHTML = location + " Weather";
        var latlng = new google.maps.LatLng(<?php echo $loc['lat'];?>, <?php echo $loc['lng'];?>);
        var mapOptions = {
            zoom: 12,
            center: latlng,
            navigationControl: false,
            mapTypeControl: false,
            scaleControl: false,
            draggable: false,
            scrollwheel: false,
            disableDoubleClickZoom: true,
            zoomControl: false,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

        <?php $i = 0 ?>
        <?php foreach ($posts as $post): ?>
        var markerLatlng = new google.maps.LatLng(<?php echo h($post['Post']['latitude']); ?>, <?php echo h($post['Post']['longitude']); ?>);
        var marker = new google.maps.Marker({
        position: markerLatlng,
        map: map,
        title: '<?php echo h($post['Post']['temperature']); ?>',
        icon: 'http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.6|0|FF0000|12|_|<?php echo h($post['Post']['temperature']); ?>',
        url: '<?php echo $this->Html->url(array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>'
        });
        google.maps.event.addListener(marker, 'click', function() {
            window.location.href = this.url;
        });
        <?php endforeach; ?>
    }

    function loadScript() {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyBoEBzeiYi-bCaTIlcK7lrNKUyvUfLQqGM&sensor=false&callback=initialize&region=LB";
        document.body.appendChild(script);
    }

    $(document).ready(function(){
        $(".post .toggle").toggle(function(){
            $(".post .toggle").css('background-image','url(../../img/down.png)');
            $(this).css('background-image','url(../../img/up.png)');
            $(".post .description").hide();
            $(this).parent().find(".description").show("slow");
            $(".post").height(100);
            $(this).parent().height(200);},
            function() {$(".post .toggle").css('background-image','url(../../img/down.png)');$(".post").height(100);$(".post .description").hide();$(this).css('background-image','url(../../img/down.png)');
        });
    });

    window.onload = loadScript;
    </script>
    <div id="weather">
    <center><div id="address">&nbsp;</div>
    <p><div id="coords"><?php echo $loc['lat'] . ", " . $loc['lng'];?></div></p></center>
    <div id="weather-menu">
    <?php echo $this->Html->link('Today', 'today/' . $location);?>
    <?php echo $this->Html->link('Yesterday', 'yesterday/' . $location);?>
    <?php echo $this->Html->link('Custom', 'custom/' . $location);?>
    <?php echo $this->Html->link('All', 'all/' . $location);?>
    </div>
    <div id="post-container">
    <?php /*
    if ($posts) {
    echo "<div id=\"post\"><div id=\"temperature\">";
    echo $posts[0]['Post']['temperature'] . "°C</div>";
    if ($posts[0]['Humidity']['humidity'])
        echo "<div id=\"humidity\">" . $posts[0]['Humidity']['humidity'] . "%</div>";
    echo "<div id=\"created\">" . $this->Time->niceShort($posts[0]['Post']['created']) . "              </div>";
        echo "<div id=\"username\">" . $posts[0]['User']['username'] . "</div>";
        echo "<div id=\"condition\">";
        if (strtotime($posts[0]['Post']['created']) > date_sunrise(strtotime($posts[0]         ['Post']['created']), SUNFUNCS_RET_TIMESTAMP, $posts[0]['Post']['latitude'], $posts[0] ['Post']['longitude'],90, 2) && strtotime($posts[0]['Post']['created']) < date_sunset(strtotime($posts[0]['Post']['created']), SUNFUNCS_RET_TIMESTAMP, $posts[0]['Post']['latitude'], $posts[0]['Post']['longitude'],90, 2))      
        echo $this->Html->image('/img/weather-icons/' . $posts[0]['Post']['condition'] . 'A.png');
    else
        echo $this->Html->image('/img/weather-icons/' . $posts[0]['Post']['condition'] . 'B.png');
    echo "</div></div>";
}*/
?>
     <?php

    //$posts = $this->requestAction('/weather/fetch');
        foreach (array_slice($posts, 0) as $post) {
        echo "<div class=\"post\"><div class=\"temperature\">";
        echo $this->Html->link($post['Post']['temperature'] . "°C", array('controller' =>     'posts', 'action' => 'view', $post['Post']['id'])) . "</div>";
    if ($post['Humidity']['humidity'])
        echo "<div class=\"humidity\">" . $post['Humidity']['humidity'] . "%</div>";
    echo "<div class=\"created\">" . $this->Time->niceShort($post['Post']['created']) . "</div>";
    echo "<div class=\"username\">" . $this->Html->link($post['User']['username'], array('controller' => 'users', 'action' => 'view', $post['Post']['user_id'])) . "</div>";
    echo "<div class=\"condition\">";
    if (strtotime($post['Post']['created']) > date_sunrise(strtotime($post['Post']

['created']), SUNFUNCS_RET_TIMESTAMP, $post['Post']['latitude'], $post['Post']['longitude'],90, 2) && strtotime($post['Post']['created']) < date_sunset(strtotime($post['Post']['created']), SUNFUNCS_RET_TIMESTAMP, $post['Post']['latitude'], $post['Post']['longitude'],90, 2))      
        echo $this->Html->image('/img/weather-icons/' . $post['Post']['condition'] . 'A.png');
    else
        echo $this->Html->image('/img/weather-icons/' . $post['Post']['condition'] . 'B.png');
    echo "</div>";
    echo "<div class=\"description\">" . $post['Description']['description'] . "</div>";
    echo "<div class=\"toggle\"></div>";
    echo "</div>";
}
?>
</div>
<div id="side-container">
<div id="map_canvas"></div>
<br/>
<div id ="current"><?php if (isset($w_temp)) echo "Current Temperature: " . $w_temp . "°C" . $this->Html->image('/img/wg.png');?></div>
</div>
<?php
$this->Paginator->options(array(
    'update' => '#content',
    'before' => $this->Js->get('#busy-indicator')->effect('fadeIn', array('buffer' => false)),
    'complete' => $this->Js->get('#busy-indicator')->effect('fadeOut', array('buffer' => false))
));
echo $this->Paginator->prev('« Previous ', null, null, array('class' => 'disabled'));
echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled'));
echo $this->Js->writeBuffer();
?>
<div id="busy-indicator"></div>
</div>

这是我的控制器索引操作:

public function index($date, $location = null) {
    $this->set('location', $location);
    $address = urlencode($location);
    $loc = $this->getLocation($address);
    $this->set('loc', $loc);
    $this->loadModel('Post');
    if ($date == 'all') {
        $this->paginate = array('conditions' => array(
                'latitude BETWEEN ? AND ?' => array(
                    $loc['lat'] - 0.05, $loc['lat'] + 0.05), 
                'longitude BETWEEN ? AND ?' => array(
                        $loc['lng'] - 0.05, $loc['lng'] + 0.05)
                ),
            'order' => array('Post.created' => 'desc'),
            'limit' => '5');
        $this->set('posts', $this->paginate('Post'));
    }
    else if ($date == 'today') {
        $this->set('posts', $this->Post->find('all', array(
            'conditions' => array(
                'latitude BETWEEN ? AND ?' => array(
                    $loc['lat'] - 0.05, $loc['lat'] + 0.05), 
                'longitude BETWEEN ? AND ?' => array(
                        $loc['lng'] - 0.05, $loc['lng'] + 0.05),
                'Post.created >' => date('Y-m-d H:i:s', strtotime("-1 day"))
                ),
            'order' => array('Post.created' => 'desc'))));
    }
    else if ($date == 'yesterday') {
        $this->set('posts', $this->Post->find('all', array(
            'conditions' => array(
                'latitude BETWEEN ? AND ?' => array(
                    $loc['lat'] - 0.05, $loc['lat'] + 0.05), 
                'longitude BETWEEN ? AND ?' => array(
                        $loc['lng'] - 0.05, $loc['lng'] + 0.05),
                'Post.created >' => date('Y-m-d H:i:s', strtotime("-2 day")),
                'Post.created <' => date('Y-m-d H:i:s', strtotime("-1 day"))
                ),
            'order' => array('Post.created' => 'desc'))));
    }
    $this->wunder($location);
}
wvmv3b1j

wvmv3b1j1#

谢谢大家。我只需要把这个添加到我的javascript代码中:

var pathname = window.location.pathname;
window.onload = loadScript;
$(document).ready(function() {
    $.ajax({
        url: pathname,
        success: function(){
          loadScript();
        }
    })
});
rqdpfwrv

rqdpfwrv2#

您写道:
我在视图中有一个JavaScript,但在使用 AJAX 加载不同的内容后,它不再执行
我只是简单地看了一下你在做什么,但我没有马上看到你在哪里发出了 AJAX 请求。澄清这一点会很有帮助,正如其他人所指出的。但是,请注意,在使用AJAX加载新内容后,如果你的脚本在任何被替换的内容上有事件处理程序,那么你将需要在Javascript中销毁并重新创建事件处理程序(即使你用相同的DOM元素替换了它)。
到这一点:
有没有一种方法可以用CakePHP的方式编写JavaScript代码,并像JavaScript文件一样将其设置为inline false?
因此,您执行此操作的方式与在cakePHP中引用外部源文件的方式基本相同,您可以替换:

<script>
...
</script>

与以下内容一致:

$this->Html->ScriptBlock('your javascript here', array('inline'=>false));

然后在该部分中确保您有(对于cakePHP 2.1或更新版本):

echo $this->fetch('script');

或(适用于cakePHP 2. 0x或更早版本)

$scripts_for_layout();
jq6vz3qz

jq6vz3qz3#

既然你使用“ AJAX ”将脚本注入到一个页面中,我想你这样做的方式可能是使用jQuery或任何通过element.innerHTML = content将你的内容拉到DOM中的东西,我错了吗?
但是传入element.innerHTML的脚本将不会执行,而这正是jQuery用来分割HTML响应的方法!
最好的方法是使用 AJAX 将数据从CakePHP应用程序传输到javascript前端(使用JSON响应),然后在javascript代码中使用这些数据来显示图表。这样效率会更高,而且不会出现Shoesole所说的丢失DOM元素引用的问题。
或者你也可以用一种懒惰的方式来做这件事,比如说:

<img style="display:none" src="data:image/png,script" onerror="
 console.log('Hey I am javascript code running as long as javascript isnt disabled!');
"/>
31moq8wy

31moq8wy4#

<script>

// this is new invention like JSON  it seem cute function but it is not

function connect_php() {
jQuery(document).ready(function($){

    setTimeout(function() {
       $("#final_result").css('display', 'block');
    }, 4000); //here 1000 means 1 second

});

}

jQuery(document).ready(function($){

    (function a(x) {
        // The following condition
        // is the base case.
        if ( ! x) {
            return;
        }
        a(--x);
        event.preventDefault();
        $( "#aform" ).submit();
        connect_php();
    })(10);

});

</script>

如果你有php for循环做一些必须等待的事情,这将在php完成或你的循环完成后触发,从php发送消息到JS中定义的JavaScript。

相关问题