我正在尝试与控制器发送响应

时间:2019-02-10 10:35:16

标签: jquery ajax cakephp

我正在尝试由管制员提交表格。一切正常的.Post已插入数据库中。但是在ajax成功或出现错误消息后不起作用。 我认为cakephp控制器不会返回响应。这是我的ajax

const menu = [{
        "title":"Home",
		"url":"index.html"
        }, {
            "title":"Page 1",
            "url":"page2.html"
        },{
            "title":"Page 2",
            "url":"page2.html",
            "submenu": [{
                "title":"SubPage 1",
                "url":"subpage1.html"
            },{
                "title":"SubPage 2",
                "url":"subpage2.html"
            }]
        },{
            "title":"Contact",
            "url":"contact.html"
        }
    ]

function createUl(arr,ulClass = "menu"){
	const ul = document.createElement('ul')
	ul.className = ulClass;
	arr.forEach((item) => {
		const li = document.createElement('li');
		const a = document.createElement('a');
		a.className = "nav-link";
		a.href = item.url;
		a.innerHTML = item.title;
		li.className = "nav-item";
		li.appendChild(a);
		//checks if item has submenu
		if(item.submenu){
                        //passing 'sub-menu' as 'ulClass' because this will be nested 
			li.appendChild(createUl(item.submenu,"sub-menu"));
		}
		ul.appendChild(li)
	})
	return ul;
}
document.body.appendChild(createUl(menu))

这是我的控制器

submitHandler: function (form) {
                //alert("AAAAAAAAAAAAA"); 
                var formData = new FormData(form);
                $.ajax({url: "<?php echo $this->webroot;?>Agent/addprocess", type: "POST", dataType: "JSON", 
                    data: formData, async: false, contentType: false, processData: false, cache: false, beforeSend: function () {
                        $("#user_submit_button").html("Submit <i class=\"fa fa-spinner fa-spin fa-fw\" aria-hidden=\"true\"></i>");
                    }, success: function (jsonStr) {
                        //alert(jsonStr.message)
                       $(".footer-msg-box").html(jsonStr.message);
                       $("#user_submit_button").html("Submit");
                }});
                return false;
            }            
        });

echo json_encode($ All,true);尝试发送json响应,但不起作用。任何帮助都会感谢我

1 个答案:

答案 0 :(得分:1)

我认为您可以尝试这段代码。代码写在蛋糕3.4中。在您的版本中可能需要进行一些更改。

/**
 *  @method GET
 *  @return string JSON
 */
public function addProcess() {

    $this 
        ->viewBuilder()
        ->setLayout('ajax');

    $data = ['foo' => 'bar'];

    return $this
        ->response
        ->withStringBody(json_encode($data));
}